﻿using BaseAuthRole.Domain.Input;
using BaseAuthRole.Domain.OutPut;
using BaseAuthRole.DTO.Auth;
using BaseAuthRole.DTO.Knowledge;
using BaseAuthRole.DTO.Knowledge.Enum;
using BaseAuthRole.DTO.Org;
using BaseAuthRole.DTO.Role;
using BaseAuthRole.DTO.User;
using BaseAuthRole.IRepository;
using BaseAuthRole.IService;
using Coldairarrow.Util;
using CSRedis;
using FreeSql;
using log4net;
using Lutos.Dictionary.SDK.Core;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using MiniExcelLibs;
using MiniExcelLibs.Attributes;
using RS.BaseModel;
using RS.BaseModel.Common;
using RS.BaseModel.Enum;
using RS.Environment;
using RS.Tool.Base;
using RS.Tool.DataBase;
using RS.Tool.Init;
using RS.Tool.SDK.FeiShu;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing.Printing;
using System.Dynamic;
using System.Linq;
using System.Net;

namespace BaseAuthRole.Service
{
    public class UserService : IUserService
    {

        private static ILog logger = log4net.LogManager.GetLogger("ThirdPartyOAuthController");

        private readonly int UserAuthTokenExpire = Convert.ToInt32(ConfigurationHelper.GetAppSettings("UserAuthTokenExpire"));

        private readonly int AppAccessTokenExpire = Convert.ToInt32(ConfigurationHelper.GetAppSettings("AppAccessTokenExpire"));

        private readonly string RoleUserExportTemplateUrl = ConfigurationHelper.GetAppSettings("RoleUserExportTemplateUrl");

        private readonly List<string> UnDelRoleIds = ConfigurationHelper.GetAppSettings("UnDelRoleIds").Split(",").ToList();

        IAuthRepository _authRepository;

        private readonly UnitOfWorkManager _unitOfWorkManager;


        private CSRedisHelper _cSRedisHelper;
        private CSRedisClient UserAuthRedis;
        private CSRedisClient ApplicationRedis;
        private CSRedisClient UserInfoRedis;
        private IFeiShuClient _feiShuClient;
        private ILtDictionaryClient _ltDictionaryClient;

        public UserService(IAuthRepository authRepository, UnitOfWorkManager unitOfWorkManager, CSRedisHelper cSRedisHelper, IFeiShuClient feiShuClient, ILtDictionaryClient ltDictionaryClient)
        {

            this._authRepository = authRepository;
            this._unitOfWorkManager = unitOfWorkManager;

            this._cSRedisHelper = cSRedisHelper;

            UserAuthRedis = _cSRedisHelper.csredis[0];

            ApplicationRedis = _cSRedisHelper.csredis[1];

            UserInfoRedis = _cSRedisHelper.csredis[2];

            _feiShuClient = feiShuClient;

            _ltDictionaryClient = ltDictionaryClient;
        }

        public void SetUserAuthTokenInRedis(UUIUserAuthToken info)
        {
            UserAuthRedis.Set(info.AuthToken, info, Convert.ToInt32((info.ExpireTime - DateTime.Now).TotalSeconds));
        }

        public UUIUserAuthToken GetUserAuthTokenFromRedis(string authToken)
        {
            var r = UserAuthRedis.Get<UUIUserAuthToken>(authToken);
            return r;
        }


        public void SetAppAccessTokenInRedis(GetAppAccessTokenModelOutPut info)
        {

            ApplicationRedis.Set(info.AppAccessToken, info, Convert.ToInt32((info.ExpireTime - DateTime.Now).TotalSeconds));

        }


        public GetAppAccessTokenModelOutPut GetAppAccessTokenFromRedis(string accessToken)
        {

            var r = ApplicationRedis.Get<GetAppAccessTokenModelOutPut>(accessToken);
            return r;

        }

        public GetUserInfoOutPut GetUserInfoFromRedis(string uid)
        {
            //先不取缓存
            return null;
            var r = UserInfoRedis.Get<GetUserInfoOutPut>(uid);
            return r;
        }



        public void SetUserInfoInRedis(GetUserInfoOutPut getUserInfoOutPut)
        {

            UserInfoRedis.Set(getUserInfoOutPut.Uid, getUserInfoOutPut);

        }


        public CommonResult<GetAppAccessTokenModelOutPut> GetAppAccessTokenModel(string appid, string secret)
        {
            var result = new CommonResult<GetAppAccessTokenModelOutPut>();

            var app = this._authRepository.Orm.Select<ApplicationModel>(new { Id = appid }).ToOne();

            if (app == null)
            {
                result.Value = EnumBaseResult.NoResource;
                result.Message = "无效的AppId";
                return result;
            }

            if (app.Secret != secret)
            {
                result.Value = EnumBaseResult.InvalidSecret;
                result.Message = "无效的密钥";
                return result;
            }
            if (app.Status != 1)
            {
                result.Value = EnumBaseResult.InvalidSecret;
                result.Message = "该应用已停用";
            }
            var app_accesstoken = new AppAccessTokenModel
            {
                AppId = appid
            };

            var GetAppAccessTokenModelOutPut = new GetAppAccessTokenModelOutPut
            {
                AppAccessToken = app_accesstoken.AppAccessToken,
                ExpireTime = app_accesstoken.ExpireTime,
                AddTime = app_accesstoken.AddTime,
                AppId = appid
            };

            this.SetAppAccessTokenInRedis(GetAppAccessTokenModelOutPut);

            result.IsError = false;
            result.Result = GetAppAccessTokenModelOutPut;
            return result;

        }
        public bool CheckUserAction(string UserId, string ActionId)
        {

            var role = _authRepository.Orm.Select<UserRoleRelation>().Where(x => x.UserId == UserId).ToList(a => a.RoleId);
            var r = _authRepository.Orm.Select<RoleActionRelation>().Any(x => role.Contains(x.RoleId) && x.ActionId == ActionId);
            return r;

        }

        public List<Role> GetCJWUserRoleRelation(string UserId)
        {

            var role = _authRepository.Orm.Select<UserRoleRelation, Role>().InnerJoin(x => x.t1.RoleId == x.t2.Id).Where(x => x.t1.UserId == UserId).ToList(x => x.t2);

            return role;
        }

        public UUIUser GetUIUser(string id)
        {
            return this._authRepository.Orm.Select<UUIUser>().Where(x => x.Id == id).ToOne();
        }

        public UUIUser GetUUIUserByUniqueId(string uniqueId)
        {

            return this._authRepository.Orm.Select<UUIUser>().Where(x => x.UniqueId == uniqueId).ToOne();


        }
        public UUIUser GetUIUserByJobNumber(string jobNumber)
        {
            string jobNumberStr = jobNumber.ToLower();
            return this._authRepository.Orm.Select<UUIUser>().Where(O => O.JobNumber == jobNumber || O.LoginName.ToLower() == jobNumberStr).ToOne();

        }

        public UUIUser GetUIUserByLoginName(string loginName)
        {
            string loginNameStr = loginName.ToLower();
            return this._authRepository.Orm.Select<UUIUser>().Where(O => O.LoginName.ToLower() == loginNameStr).ToOne();

        }


        public UUIUser GetUIUser(string login_name, string password)
        {
            return this._authRepository.Orm.Select<UUIUser>().Where(x => x.LoginName.ToLower() == login_name.ToLower() && x.PassWord == password).ToOne();

        }

        public UUIUser GetUIUser(object obj)
        {

            return this._authRepository.Orm.Select<UUIUser>(obj).ToOne();


        }

        public CommonResult<UUIUser> PublicAppAuthorizeCheck(string appid, string uid, string authType, string redirect_uri)
        {

            var result = new CommonResult<UUIUser>();

            var authTypeByte = authType.Split(',');

            var authAllType = EnumHelper.GetAllName<UUIUserAuthType>();

            foreach (var o in authTypeByte)
            {
                if (!authAllType.Any(p => p == o))
                {
                    result.Message = "授权类型有误";
                    result.Value = EnumBaseResult.NoRight;
                    return result;
                }
            }

            //检查应用

            if (string.IsNullOrEmpty(redirect_uri))
            {
                result.Message = "回调不能为空";
                result.Value = EnumBaseResult.NoRight;
                return result;
            }

            var app = this._authRepository.Orm.Select<ApplicationModel>().Where(o => o.Id == appid).ToOne();

            if (app == null)
            {

                result.Message = "无效的AppId";
                result.Value = EnumBaseResult.NoRight;
                return result;
            }

            if (app.Status != 1)
            {

                result.Message = "该应用已被禁用";
                result.Value = EnumBaseResult.NoRight;
                return result;
            }

            var AuthDomain = app.AuthDomain.Split(';').ToList();


            if (AuthDomain.Any(o => redirect_uri.StartsWith("http://" + o) || redirect_uri.StartsWith("https://" + o) || redirect_uri.StartsWith(o)))
            {



            }
            else
            {

                result.Message = "非法的回调域";
                result.Value = EnumBaseResult.NoRight;
                return result;
            }


            //检查用户
            var user = this.GetUIUser(uid);

            if (user == null)
            {

                result.Message = "无效的用户";
                result.Value = EnumBaseResult.NoRight;
                return result;
            }

            if (user.Status != 1)
            {

                result.Message = "该用户已被禁用";
                result.Value = EnumBaseResult.NoRight;
                return result;
            }

            //检查是否有权限
            var checkAction = this.CheckUserAction(user.Id, app.Id);

            if (!checkAction)
            {

                result.Message = "该用户无权限访问该应用";
                result.Value = EnumBaseResult.NoRight;
                return result;
            }


            result.IsError = false;

            result.Result = user;

            return result;


        }

        public CommonResult AccessTokenCheck(string appid, string accessToken)
        {

            var result = new CommonResult();

            var info = this.GetAppAccessTokenFromRedis(accessToken);

            if (info == null)
            {

                result.Value = EnumBaseResult.NoRight;
                result.Message = "无效的accessToken";
                return result;

            }

            if (!string.Equals(appid, info.AppId))
            {

                result.Value = EnumBaseResult.NoRight;
                result.Message = "无效的accessToken";
                return result;

            }

            result.IsError = false;

            return result;


        }
        public CommonResult GetUserAuthCode(string appid, string uid, string authType, string redirect_uri)
        {

            var result = new CommonResult();

            var authTypeByte = authType.Split(',');

            var authAllType = EnumHelper.GetAllName<UUIUserAuthType>();

            foreach (var o in authTypeByte)
            {
                if (!authAllType.Any(p => p == o))
                {
                    result.Message = "授权类型有误";
                    result.Value = EnumBaseResult.NoRight;
                    return result;
                }
            }

            //检查应用

            if (string.IsNullOrEmpty(redirect_uri))
            {
                result.Message = "回调不能为空";
                result.Value = EnumBaseResult.NoRight;
                return result;
            }

            var app = this._authRepository.Orm.Select<ApplicationModel>().Where(o => o.Id == appid).ToOne();

            if (app == null)
            {

                result.Message = "无效的AppId";
                result.Value = EnumBaseResult.NoRight;
                return result;
            }

            if (app.Status != 1)
            {

                result.Message = "该应用已被禁用";
                result.Value = EnumBaseResult.NoRight;
                return result;
            }

            var AuthDomain = app.AuthDomain.Split(';').ToList();

            if (AuthDomain.Any(o => redirect_uri.StartsWith("http://" + o) || redirect_uri.StartsWith("https://" + o) || redirect_uri.StartsWith(o)))
            {

            }
            else
            {
                result.Message = "非法的回调域";
                result.Value = EnumBaseResult.NoRight;
                return result;
            }

            //检查用户
            var user = this.GetUIUser(uid);

            if (user == null)
            {

                result.Message = "无效的用户";
                result.Value = EnumBaseResult.NoRight;
                return result;
            }

            if (user.Status != 1)
            {

                result.Message = "该用户已被禁用";
                result.Value = EnumBaseResult.NoRight;
                return result;
            }

            //检查是否有权限
            logger.Debug($"检查是否有权限:user.Id:{user.Id} app.Id:{app.Id}");
            var checkAction = this.CheckUserAction(user.Id, app.Id);

            if (!checkAction)
            {

                result.Message = "该用户无权限访问该应用";
                result.Value = EnumBaseResult.NoRight;
                return result;
            }

            var code = new UUIUserAuthCode
            {
                AuthType = authType,
                Uid = uid,
                AppId = appid,
                UserUniqueId = user.UniqueId
            };

            var info = this._authRepository.Orm.Insert(code).ExecuteAffrows();

            if (info > 0)
            {
                result.IsError = false;
                result.Result = code.Id;
            }
            else
            {
                result.Value = EnumBaseResult.NoRight;
                result.Message = "操作失败";
            }
            return result;
        }
        /// <summary>
        /// 获取用户授权
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public CommonResult<GetUserAuthTokenOutput> GetUserAuthToken(string appid, string code)
        {

            var result = new CommonResult<GetUserAuthTokenOutput>();

            var auth_code = this._authRepository.Orm.Select<UUIUserAuthCode>().Where(o => o.Id == code).ToOne();

            //if (auth_code == null || auth_code.ExpirTime < DateTimeOffset.Now || auth_code.AppId != appid)
            //暂时允许A应用使用B应用的auth_code
            if (auth_code == null || auth_code.ExpirTime < DateTimeOffset.Now)
            {
                result.Value = EnumBaseResult.NoRight;
                result.Message = "无效的code";
                return result;
            }

            var user = this.GetUIUser(auth_code.Uid);

            if (user == null)
            {

                result.Value = EnumBaseResult.NoRight;
                result.Message = "用户不存在";
                return result;
            }

            var UUIUserAuthToken = new UUIUserAuthToken
            {
                Uid = user.Id,
                UserUniqueId = user.UniqueId,
                AuthType = auth_code.AuthType,
                AppId = auth_code.AppId,
                AuthCode = auth_code.Id
            };

            UUIUserAuthToken.SetAuthToken();


            var GeUserAuthTokenOutput = new GetUserAuthTokenOutput
            {

                ExpireTime = UUIUserAuthToken.ExpireTime,
                AuthToken = UUIUserAuthToken.AuthToken
            };


            this.SetUserAuthTokenInRedis(UUIUserAuthToken);


            result.IsError = false;
            result.Result = GeUserAuthTokenOutput;
            return result;

        }
        [Obsolete]
        public CommonResult GetUserInfo(string token, string appid)
        {

            var result = new CommonResult();

            var access_token = this._authRepository.Orm.Select<UUIUserAuthToken>().Where(o => o.Id == token).ToOne();

            if (access_token == null || access_token.ExpireTime < DateTime.UtcNow.AddHours(8) || appid != access_token.AppId)
            {

                result.Message = "无效的授权Token";
                result.Value = EnumBaseResult.NoRight;
                return result;

            }
            else
            {
                var user = this.GetUIUser(access_token.Uid);

                var auth_type_byte = access_token.AuthType.Split(',');

                dynamic result_obj = new ExpandoObject();

                result_obj.uuid = user.UniqueId;

                foreach (var o in auth_type_byte)
                {

                    switch (Enum.Parse(typeof(UUIUserAuthType), o, true))
                    {

                        case UUIUserAuthType.auth_base:
                            result_obj.name = user.Name;
                            result_obj.job_number = user.JobNumber;
                            result_obj.department = user.Department;
                            result_obj.title = user.Title;
                            result_obj.job_title = user.JobTitle;
                            result_obj.profession = user.Profession;

                            break;

                        case UUIUserAuthType.auth_info:
                            result_obj.name = user.Name;
                            result_obj.job_number = user.JobNumber;
                            result_obj.department = user.Department;
                            result_obj.title = user.Title;
                            result_obj.job_title = user.JobTitle;
                            result_obj.profession = user.Profession;

                            break;
                    }
                }

                result.IsError = false;
                result.Result = result_obj;
            }
            return result;


        }
        /// <summary>
        /// Token交换用户信息
        /// </summary>
        /// <param name="getUserInfoInput"></param>
        /// <returns></returns>
        public CommonResult<GetUserInfoOutPut> GetUserInfo(GetUserInfoInput getUserInfoInput)
        {

            var result = new CommonResult<GetUserInfoOutPut>();

            var user_Token = this.GetUserAuthTokenFromRedis(getUserInfoInput.AuthToken);

            if (user_Token == null)
            {
                result.Value = EnumBaseResult.NoLogin;
                return result;
            }

            //缺少appid与user_Token.appid 校验


            var userInfo = this.GetUserInfoFromRedis(user_Token.Uid);

            if (userInfo != null)
            {

                result.IsError = false;
                result.Result = userInfo;
                return result;

            }

            var user = this.GetUIUser(user_Token.Uid);

            var auth_type_byte = user_Token.AuthType.Split(',');

            userInfo = new GetUserInfoOutPut();

            foreach (var o in auth_type_byte)
            {

                switch (Enum.Parse(typeof(UUIUserAuthType), o, true))
                {

                    case UUIUserAuthType.auth_base:
                        userInfo.Uid = user.Id;
                        userInfo.Name = user.Name;
                        userInfo.JobNumber = user.JobNumber;
                        userInfo.Avatar = user.Avatar;
                        userInfo.NickName = user.NickName;
                        userInfo.Department = user.Department;
                        userInfo.Title = user.Title;
                        userInfo.Profession = user.Profession;
                        userInfo.JobTitle = user.JobTitle;
                        userInfo.Phone = user.Phone;
                        userInfo.DepartmentId = user.DepartmentId;
                        userInfo.Email = user.Email;
                        userInfo.EmployeeType = user.EmployeeType;
                        userInfo.Gender = user.Gender;
                        userInfo.IdCardNo = user.IdCardNo;
                        userInfo.JobState = user.JobState;
                        userInfo.Nation = user.Nation;
                        userInfo.Nationality = user.Nationality;
                        userInfo.NationalityCode = user.NationalityCode;
                        userInfo.NationPlace = user.NationPlace;
                        userInfo.TopQualifications = user.TopQualifications;
                        userInfo.FeiShuUid = user.FeiShuUid;
                        userInfo.LoginName = user.LoginName;
                        break;

                    case UUIUserAuthType.auth_info:
                        userInfo.Uid = user.Id;
                        userInfo.Name = user.Name;
                        userInfo.JobNumber = user.JobNumber;
                        userInfo.Avatar = user.Avatar;
                        userInfo.NickName = user.NickName;
                        userInfo.Department = user.Department;
                        userInfo.Title = user.Title;
                        userInfo.Profession = user.Profession;
                        userInfo.JobTitle = user.JobTitle;
                        user.Phone = user.Phone;
                        userInfo.DepartmentId = user.DepartmentId;
                        userInfo.Email = user.Email;
                        userInfo.EmployeeType = user.EmployeeType;
                        userInfo.Gender = user.Gender;
                        userInfo.IdCardNo = user.IdCardNo;
                        userInfo.JobState = user.JobState;
                        userInfo.Nation = user.Nation;
                        userInfo.Nationality = user.Nationality;
                        userInfo.NationalityCode = user.NationalityCode;
                        userInfo.NationPlace = user.NationPlace;
                        userInfo.TopQualifications = user.TopQualifications;
                        userInfo.FeiShuUid = user.FeiShuUid;
                        userInfo.LoginName = user.LoginName;
                        break;
                }
            }


            var roles = this._authRepository.Orm.Select<UserRoleRelation>().Where(o => o.UserId == user.Id).ToList(o => o.RoleId);

            var actions = this._authRepository.Orm.Select<DTO.Role.Action, RoleActionRelation>().LeftJoin((o, p) => o.Id == p.ActionId).Where((o, p) => roles.Contains(p.RoleId)).ToList();

            userInfo.Actions = actions;

            this.SetUserInfoInRedis(userInfo);

            result.IsError = false;

            result.Result = userInfo;

            return result;
        }

        /// <summary>
        /// Token交换用户详情信息
        /// </summary>
        /// <param name="getUserInfoInput"></param>
        /// <returns></returns>
        public CommonResult<GetUserDetailInfoOutPut> GetUserDetailInfo(GetUserInfoInput getUserInfoInput)
        {

            var result = new CommonResult<GetUserDetailInfoOutPut>();

            var user_Token = this.GetUserAuthTokenFromRedis(getUserInfoInput.AuthToken);

            if (user_Token == null)
            {
                result.Value = EnumBaseResult.NoLogin;
                return result;
            }

            var userDetailInfo = new GetUserDetailInfoOutPut();

            var user = this.GetUIUser(user_Token.Uid);

            var auth_type_byte = user_Token.AuthType.Split(',');

            var userInfo = new GetUserDetailInfoOutPut();

            foreach (var o in auth_type_byte)
            {

                switch (Enum.Parse(typeof(UUIUserAuthType), o, true))
                {

                    case UUIUserAuthType.auth_base:
                        userInfo.Uid = user.Id;
                        userInfo.Name = user.Name;
                        userInfo.JobNumber = user.JobNumber;
                        userInfo.Avatar = user.Avatar;
                        userInfo.NickName = user.NickName;
                        userInfo.Department = user.Department;
                        userInfo.Title = user.Title;
                        userInfo.Profession = user.Profession;
                        userInfo.JobTitle = user.JobTitle;
                        userInfo.Phone = user.Phone;
                        userInfo.DepartmentId = user.DepartmentId;
                        userInfo.Email = user.Email;
                        userInfo.EmployeeType = user.EmployeeType;
                        userInfo.Gender = user.Gender;
                        userInfo.IdCardNo = user.IdCardNo;
                        userInfo.JobState = user.JobState;
                        userInfo.Nation = user.Nation;
                        userInfo.Nationality = user.Nationality;
                        userInfo.NationalityCode = user.NationalityCode;
                        userInfo.NationPlace = user.NationPlace;
                        userInfo.TopQualifications = user.TopQualifications;
                        userInfo.FeiShuUid = user.FeiShuUid;
                        userInfo.LoginName = user.LoginName;
                        break;

                    case UUIUserAuthType.auth_info:
                        userInfo.Uid = user.Id;
                        userInfo.Name = user.Name;
                        userInfo.JobNumber = user.JobNumber;
                        userInfo.Avatar = user.Avatar;
                        userInfo.NickName = user.NickName;
                        userInfo.Department = user.Department;
                        userInfo.Title = user.Title;
                        userInfo.Profession = user.Profession;
                        userInfo.JobTitle = user.JobTitle;
                        user.Phone = user.Phone;
                        userInfo.DepartmentId = user.DepartmentId;
                        userInfo.Email = user.Email;
                        userInfo.EmployeeType = user.EmployeeType;
                        userInfo.Gender = user.Gender;
                        userInfo.IdCardNo = user.IdCardNo;
                        userInfo.JobState = user.JobState;
                        userInfo.Nation = user.Nation;
                        userInfo.Nationality = user.Nationality;
                        userInfo.NationalityCode = user.NationalityCode;
                        userInfo.NationPlace = user.NationPlace;
                        userInfo.TopQualifications = user.TopQualifications;
                        userInfo.FeiShuUid = user.FeiShuUid;
                        userInfo.LoginName = user.LoginName;
                        break;
                }
            }

            if (!string.IsNullOrEmpty(userInfo.DepartmentId))
            {
                var departmentName = this._authRepository.Orm.Select<Organization>().Where(p => p.Id == userInfo.DepartmentId).First(p => p.OrgName);
                userInfo.Department = departmentName == null ? "" : departmentName;
            }

            var roleActionRelations = this._authRepository.Orm.Select<UserRoleRelation>().Where(o => o.UserId == user.Id).ToList(o => o.RoleId);

            var roles = this._authRepository.Orm.Select<DTO.Role.Role>().Where(p => roleActionRelations.Contains(p.Id)).ToList();

            var actions = this._authRepository.Orm.Select<DTO.Role.Action, RoleActionRelation>().LeftJoin((o, p) => o.Id == p.ActionId).Where((o, p) => roleActionRelations.Contains(p.RoleId)).ToList();

            userInfo.Actions = actions;

            userInfo.Roles = roles;

            this.SetUserInfoInRedis(userInfo);

            result.IsError = false;

            result.Result = userInfo;

            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public CommonResult<GetUserInfoOutPut> GetUserInfoByUid(GetUserInfoByUidInput input)
        {

            var result = new CommonResult<GetUserInfoOutPut>();

            var userInfo = this.GetUserInfoFromRedis(input.Uid);

            if (userInfo != null)
            {

                result.IsError = false;
                result.Result = userInfo;
                return result;

            }

            var user = this.GetUIUser(input.Uid);

            if (user == null)
            {
                result.IsError = false;
                result.Result = null;
                return result;
            }

            userInfo = new GetUserInfoOutPut();

            userInfo.Uid = user.Id;
            userInfo.Name = user.Name;
            userInfo.JobNumber = user.JobNumber;
            userInfo.Avatar = user.Avatar;
            userInfo.NickName = user.NickName;
            userInfo.Department = user.Department;
            userInfo.Title = user.Title;
            userInfo.Profession = user.Profession;
            userInfo.JobTitle = user.JobTitle;
            user.Phone = user.Phone;
            userInfo.DepartmentId = user.DepartmentId;
            userInfo.Email = user.Email;
            userInfo.EmployeeType = user.EmployeeType;
            userInfo.Gender = user.Gender;
            userInfo.IdCardNo = user.IdCardNo;
            userInfo.JobState = user.JobState;
            userInfo.Nation = user.Nation;
            userInfo.Nationality = user.Nationality;
            userInfo.NationalityCode = user.NationalityCode;
            userInfo.NationPlace = user.NationPlace;
            userInfo.TopQualifications = user.TopQualifications;
            userInfo.LoginName = user.LoginName;
            userInfo.FeiShuUid = user.FeiShuUid;
            userInfo.ExtFeiShuUid = user.ExtFeiShuUid;
            userInfo.Company = user.Company;
            userInfo.CompanyNo = user.CompanyNo;
            userInfo.Managerid = user.Managerid;


            var roles = this._authRepository.Orm.Select<UserRoleRelation>().Where(o => o.UserId == user.Id).ToList(o => o.RoleId);

            var actions = this._authRepository.Orm.Select<DTO.Role.Action, RoleActionRelation>().LeftJoin((o, p) => o.Id == p.ActionId).Where((o, p) => roles.Contains(p.RoleId)).ToList();

            userInfo.Actions = actions;


            this.SetUserInfoInRedis(userInfo);

            result.IsError = false;

            result.Result = userInfo;

            return result;


        }


        public CommonResult<GetUserInfoOutPut> GetUserInfoByJobNumber(GetUserInfoByJobNumberInput input)
        {

            var result = new CommonResult<GetUserInfoOutPut>();

            var user = this.GetUIUserByJobNumber(input.JobNumber);

            if (user == null)
            {


                result.Value = EnumBaseResult.NoResource;
                result.Message = "";
                return result;
            }

            var userInfo = new GetUserInfoOutPut();

            userInfo.Uid = user.Id;
            userInfo.Name = user.Name;
            userInfo.JobNumber = user.JobNumber;
            userInfo.Avatar = user.Avatar;
            userInfo.NickName = user.NickName;
            userInfo.Department = user.Department;
            userInfo.Title = user.Title;
            userInfo.Profession = user.Profession;
            userInfo.JobTitle = user.JobTitle;
            user.Phone = user.Phone;
            userInfo.DepartmentId = user.DepartmentId;
            userInfo.Email = user.Email;
            userInfo.EmployeeType = user.EmployeeType;
            userInfo.Gender = user.Gender;
            userInfo.IdCardNo = user.IdCardNo;
            userInfo.JobState = user.JobState;
            userInfo.Nation = user.Nation;
            userInfo.Nationality = user.Nationality;
            userInfo.NationalityCode = user.NationalityCode;
            userInfo.NationPlace = user.NationPlace;
            userInfo.TopQualifications = user.TopQualifications;
            userInfo.FeiShuUid = user.FeiShuUid;
            userInfo.ExtFeiShuUid = user.ExtFeiShuUid;
            userInfo.LoginName = user.LoginName;
            userInfo.Company = user.Company;
            userInfo.CompanyNo = user.CompanyNo;
            userInfo.Managerid = user.Managerid;

            var roles = this._authRepository.Orm.Select<UserRoleRelation>().Where(o => o.UserId == user.Id).ToList(o => o.RoleId);

            var actions = this._authRepository.Orm.Select<DTO.Role.Action, RoleActionRelation>().LeftJoin((o, p) => o.Id == p.ActionId).Where((o, p) => roles.Contains(p.RoleId)).ToList();

            userInfo.Actions = actions;

            this.SetUserInfoInRedis(userInfo);

            result.IsError = false;

            result.Result = userInfo;

            return result;


        }

        public CommonResult<GetUserInfoOutPut> GetUserInfoByLoginName(GetUserInfoByLoginNameInput input)
        {

            var result = new CommonResult<GetUserInfoOutPut>();

            var user = this.GetUIUserByLoginName(input.LoginName);

            if (user == null)
            {


                result.Value = EnumBaseResult.NoResource;
                result.Message = "";
                return result;
            }

            var userInfo = new GetUserInfoOutPut();

            userInfo.Uid = user.Id;
            userInfo.Name = user.Name;
            userInfo.JobNumber = user.JobNumber;
            userInfo.Avatar = user.Avatar;
            userInfo.NickName = user.NickName;
            userInfo.Department = user.Department;
            userInfo.Title = user.Title;
            userInfo.Profession = user.Profession;
            userInfo.JobTitle = user.JobTitle;
            user.Phone = user.Phone;
            userInfo.DepartmentId = user.DepartmentId;
            userInfo.Email = user.Email;
            userInfo.EmployeeType = user.EmployeeType;
            userInfo.Gender = user.Gender;
            userInfo.IdCardNo = user.IdCardNo;
            userInfo.JobState = user.JobState;
            userInfo.Nation = user.Nation;
            userInfo.Nationality = user.Nationality;
            userInfo.NationalityCode = user.NationalityCode;
            userInfo.NationPlace = user.NationPlace;
            userInfo.TopQualifications = user.TopQualifications;
            userInfo.FeiShuUid = user.FeiShuUid;
            userInfo.ExtFeiShuUid = user.ExtFeiShuUid;
            userInfo.LoginName = user.LoginName;
            userInfo.Company = user.Company;
            userInfo.CompanyNo = user.CompanyNo;
            userInfo.Managerid = user.Managerid;

            var roles = this._authRepository.Orm.Select<UserRoleRelation>().Where(o => o.UserId == user.Id).ToList(o => o.RoleId);

            var actions = this._authRepository.Orm.Select<DTO.Role.Action, RoleActionRelation>().LeftJoin((o, p) => o.Id == p.ActionId).Where((o, p) => roles.Contains(p.RoleId)).ToList();

            userInfo.Actions = actions;

            this.SetUserInfoInRedis(userInfo);

            result.IsError = false;

            result.Result = userInfo;

            return result;


        }


        public CommonResult<PageModel<GetUserInfoOutPut>> GetUserInfoList(GetUserInfoListInput input)
        {

            var result = new CommonResult<PageModel<GetUserInfoOutPut>>();

            var info = new List<GetUserInfoOutPut>();


            var query = this._authRepository.Orm.Select<UUIUser>();

            if (input.Uids.IsNotEmptyOrNull() && input.Uids.Count() > 0)
            {
                query = query.Where(o => input.Uids.Contains(o.Id));
            }

            if (!string.IsNullOrEmpty(input.EmployeeTypes))
            {
                var temp_list = input.EmployeeTypes.Split(";").ToList();
                query = query.Where(o => temp_list.Contains(o.EmployeeType));
            }

            if (!string.IsNullOrEmpty(input.DepartmentIds))
            {

                var temp_list = input.DepartmentIds.Split(";").ToList();

                query = query.Where(o => input.DepartmentIds.Contains(o.DepartmentId));
            }
            long count = 0;
            info = query.OrderByDescending(o => o.CreateTime).Count(out count).
                Page(input.Page, input.PageSize).ToList<GetUserInfoOutPut>(o => new GetUserInfoOutPut
                {
                    Uid = o.Id,
                    Avatar = o.Avatar,
                    Department = o.Department,
                    JobNumber = o.JobNumber,
                    JobTitle = o.JobTitle,
                    Name = o.Name,
                    NickName = o.NickName,
                    Phone = o.Phone,
                    Profession = o.Profession,
                    Title = o.Title,
                    FeiShuUid = o.FeiShuUid,
                    ExtFeiShuUid = o.ExtFeiShuUid,
                    DepartmentId = o.DepartmentId,
                    Email = o.Email,
                    EmployeeType = o.EmployeeType,
                    Gender = o.Gender,
                    IdCardNo = o.IdCardNo,
                    JobState = o.JobState,
                    Nation = o.Nation,
                    Nationality = o.Nationality,
                    NationalityCode = o.NationalityCode,
                    NationPlace = o.NationPlace,
                    TopQualifications = o.TopQualifications,
                    Company = o.Company,
                    CompanyNo = o.CompanyNo,
                    Managerid = o.Managerid,
                    LoginName = o.LoginName

                });

            result.IsError = false;
            result.Result = new PageModel<GetUserInfoOutPut>
            {
                Data = info,
                DataCount = count,
                Page = input.Page,
                PageSize = input.PageSize,
                PageCount = Convert.ToInt32(Math.Ceiling((decimal)count / input.PageSize))
            };
            return result;
        }

        public CommonResult<PageModel<GetSimpleUserInfoOutPut>> GetSimpleUserInfoList(GetUserInfoListInput input)
        {

            var result = new CommonResult<PageModel<GetSimpleUserInfoOutPut>>();

            var info = new List<GetSimpleUserInfoOutPut>();


            var query = this._authRepository.Orm.Select<UUIUser>();

            if (input.Uids.IsNotEmptyOrNull() && input.Uids.Count() > 0)
            {
                query = query.Where(o => input.Uids.Contains(o.Id));
            }

            if (!string.IsNullOrEmpty(input.EmployeeTypes))
            {
                var temp_list = input.EmployeeTypes.Split(";").ToList();
                query = query.Where(o => temp_list.Contains(o.EmployeeType));
            }

            if (!string.IsNullOrEmpty(input.JobNumbers))
            {
                var temp_list = input.JobNumbers.Split(";").ToList();
                query = query.Where(o => temp_list.Contains(o.JobNumber));
            }

            if (!string.IsNullOrEmpty(input.DepartmentIds))
            {

                var temp_list = input.DepartmentIds.Split(";").ToList();

                query = query.Where(o => input.DepartmentIds.Contains(o.DepartmentId));
            }
            long count = 0;
            info = query.OrderByDescending(o => o.CreateTime).Count(out count).
                Page(input.Page, input.PageSize).ToList<GetSimpleUserInfoOutPut>(o => new GetSimpleUserInfoOutPut
                {
                    Uid = o.Id,
                    JobNumber = o.JobNumber,
                    Name = o.Name,
                    JobState = o.JobState,
                    LoginName = o.LoginName

                });

            result.IsError = false;
            result.Result = new PageModel<GetSimpleUserInfoOutPut>
            {
                Data = info,
                DataCount = count,
                Page = input.Page,
                PageSize = input.PageSize,
                PageCount = Convert.ToInt32(Math.Ceiling((decimal)count / input.PageSize))
            };
            return result;
        }

        /// <summary>
        ///  获取角色用户列表(客户端)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public CommonResult<PageModel<GetUserInfoClientOutPut>> GetRoleUserInfoList(GetRoleUserPageListClientInput input)
        {
            var result = new CommonResult<PageModel<GetUserInfoClientOutPut>>();

            var info = new List<GetUserInfoClientOutPut>();

            long count = 0;

            info = this._authRepository.Orm.Select<UUIUser, UserRoleRelation>()
                .InnerJoin((a, b) => a.Id == b.UserId && b.RoleId == input.RoleId)
                .WhereIf(!string.IsNullOrEmpty(input.KeyWord), (a, b) => a.Name.ToLower().Contains(input.KeyWord.ToLower()) || a.LoginName.ToLower().Contains(input.KeyWord.ToLower()))
                .OrderByDescending((a, b) => a.CreateTime)
                .Count(out count)
                .Page(input.Page, input.PageSize)
                .ToList<GetUserInfoClientOutPut>((o, b) => new GetUserInfoClientOutPut
                {
                    Uid = o.Id,
                    Avatar = o.Avatar,
                    Department = o.Department,
                    JobNumber = o.JobNumber,
                    JobTitle = o.JobTitle,
                    Name = o.Name,
                    NickName = o.NickName,
                    Phone = o.Phone,
                    Profession = o.Profession,
                    Title = o.Title,
                    FeiShuUid = o.FeiShuUid,
                    DepartmentId = o.DepartmentId,
                    Email = o.Email,
                    EmployeeType = o.EmployeeType,
                    Gender = o.Gender,
                    IdCardNo = o.IdCardNo,
                    JobState = o.JobState,
                    Nation = o.Nation,
                    Nationality = o.Nationality,
                    NationalityCode = o.NationalityCode,
                    NationPlace = o.NationPlace,
                    TopQualifications = o.TopQualifications,
                    Company = o.Company,
                    LoginName = o.LoginName
                });

            result.IsError = false;
            result.Result = new PageModel<GetUserInfoClientOutPut>
            {
                Data = info,
                DataCount = count,
                Page = input.Page,
                PageSize = input.PageSize,
                PageCount = Convert.ToInt32(Math.Ceiling((decimal)count / input.PageSize))
            };
            return result;
        }

        /// <summary>
        /// 导出角色信息
        /// </summary>
        public class ExportRoleInfo
        {
            [ExcelColumnWidth(50)]
            [DisplayName("角色/Role")]
            public string RoleName { get; set; }

            [ExcelColumnWidth(50)]
            [DisplayName("权限类别/AuthorityType")]
            public string TypeName { get; set; }

            [ExcelColumnWidth(50)]
            [DisplayName("权限/Authority")]
            public string ActionName { get; set; }

            [ExcelColumnWidth(50)]
            [DisplayName("是否拥有/IsBelong")]
            public string IsBelong { get; set; }
        }

        /// <summary>
        /// 导出角色
        /// </summary>
        /// <returns></returns>
        public CommonResult<ExportDocumentOutPut> ExportRole(ExportRoleClientInput input)
        {
            var result = new CommonResult<ExportDocumentOutPut>();

            //获取角色列表
            var roles = _authRepository.Orm.Select<Role>()
                .WhereIf(!string.IsNullOrEmpty(input.Name), p => p.Name.Contains(input.Name))
                .ToList(p => new
                {
                    p.Id,
                    p.Name
                });

            //获取所有权限类别及权限
            var actionGroups = GetActionGroup();

            //获取角色拥有的权限
            var roleIds = roles.Select(p => p.Id).ToList();
            var roleActionRelations = _authRepository.Orm.Select<RoleActionRelation>()
                .Where(p => roleIds.Contains(p.RoleId))
                .ToList();


            var values = new List<ExportRoleInfo>();
            foreach (var role in roles)
            {
                foreach (var actionGroup in actionGroups)
                {
                    foreach (var action in actionGroup.Actions)
                    {
                        values.Add(new ExportRoleInfo
                        {
                            RoleName = role.Name,
                            TypeName = actionGroup.Name,
                            ActionName = action.ActionName,
                            IsBelong = roleActionRelations.Any(p => p.RoleId == role.Id && p.ActionId == action.Id) == true ? "是" : "否"
                        });
                    }
                }
            };

            var memoryStream = new MemoryStream();
            memoryStream.SaveAs(values);
            memoryStream.Seek(0, SeekOrigin.Begin);

            result.IsError = false;
            result.Message = "获取成功";
            result.Value = RS.BaseModel.Enum.EnumBaseResult.OK;
            result.Result = new ExportDocumentOutPut()
            {
                FileName = $"角色_{DateTime.UtcNow.AddHours(8).ToString("yyyyMMddHHmmss")}.xlsx",
                MemoryStream = memoryStream
            };

            return result;
        }

        /// <summary>
        /// 获取用户列表(客户端)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public CommonResult<PageModel<GetUserInfoClientOutPut>> GetUserInfoList(GetUserInfoListClientInput input)
        {

            var result = new CommonResult<PageModel<GetUserInfoClientOutPut>>();

            var info = new List<GetUserInfoClientOutPut>();


            var query = this._authRepository.Orm.Select<UUIUser>();

            if (input.Uids.IsNotEmptyOrNull() && input.Uids.Count() > 0)
            {
                query = query.Where(o => input.Uids.Contains(o.Id));
            }

            if (!string.IsNullOrEmpty(input.EmployeeTypes))
            {
                var temp_list = input.EmployeeTypes.Split(";").ToList();
                query = query.Where(o => temp_list.Contains(o.EmployeeType));
            }

            if (!string.IsNullOrEmpty(input.DepartmentIds))
            {
                var temp_list = input.DepartmentIds.Split(";").ToList();
                //获取第一个组织
                var departmentId = temp_list.FirstOrDefault();
                if (departmentId != null)
                {
                    var department = this._authRepository.Orm.Select<Organization>().Where(p => p.Id == departmentId).First();
                    if (department != null && department.ParentId == "0")
                    {

                    }
                    else
                    {
                        query = query.Where(o => temp_list.Contains(o.DepartmentId));
                    }
                }
            }

            if (!string.IsNullOrEmpty(input.KeyWord))
            {
                query = query.Where(o => o.Name.ToLower().Contains(input.KeyWord.ToLower()) || o.LoginName.ToLower().Contains(input.KeyWord.ToLower()));
            }
            if (input.IsAll == null || input.IsAll == false)
            {
                var orgList = this._authRepository.Orm.Select<Organization>().ToList();
                var orgNoDisplayList = orgList.Where(o => o.State == 0).ToList();
                List<Organization> allNoDisplayList = new List<Organization>();
                GetAllNoDisplayList(orgList, orgNoDisplayList, ref allNoDisplayList);
                var allNotDepart = allNoDisplayList.Select(m => m.Id).ToList();
                query.Where(m => !allNotDepart.Contains(m.DepartmentId));
            }
            long count = 0;
            info = query.OrderByDescending(o => o.CreateTime).Count(out count).
                Page(input.Page, input.PageSize).ToList<GetUserInfoClientOutPut>(o => new GetUserInfoClientOutPut
                {
                    Uid = o.Id,
                    Avatar = o.Avatar,
                    Department = o.Department,
                    JobNumber = o.JobNumber,
                    JobTitle = o.JobTitle,
                    Name = o.Name,
                    NickName = o.NickName,
                    Phone = o.Phone,
                    Profession = o.Profession,
                    Title = o.Title,
                    FeiShuUid = o.FeiShuUid,
                    DepartmentId = o.DepartmentId,
                    Email = o.Email,
                    EmployeeType = o.EmployeeType,
                    Gender = o.Gender,
                    IdCardNo = o.IdCardNo,
                    JobState = o.JobState,
                    Nation = o.Nation,
                    Nationality = o.Nationality,
                    NationalityCode = o.NationalityCode,
                    NationPlace = o.NationPlace,
                    TopQualifications = o.TopQualifications,
                    Company = o.Company,
                    LoginName = o.LoginName
                });

            //获取所有对应的组织Id
            var departmentIds = info.Select(p => p.DepartmentId).ToList();
            var departments = this._authRepository.Orm.Select<Organization>().Where(p => departmentIds.Contains(p.Id)).ToList(p => new
            {
                p.Id,
                p.OrgName
            });

            foreach (var item in info)
            {
                var department = departments.Where(p => p.Id == item.DepartmentId).FirstOrDefault();
                item.Department = department == null ? "" : department.OrgName;
            }

            result.IsError = false;
            result.Result = new PageModel<GetUserInfoClientOutPut>
            {
                Data = info,
                DataCount = count,
                Page = input.Page,
                PageSize = input.PageSize,
                PageCount = Convert.ToInt32(Math.Ceiling((decimal)count / input.PageSize))
            };
            return result;
        }

        public void GetAllNoDisplayList(List<Organization> orgList, List<Organization> orgNoDisplayList, ref List<Organization> allNoDisplayList)
        {
            foreach (Organization org in orgNoDisplayList)
            {
                allNoDisplayList.Add(org);
                GetAllNoDisplayList(orgList, orgList.Where(m => m.ParentId == org.Id).ToList(), ref allNoDisplayList);
            }
        }

        /// <summary>
        /// 添加角色用户
        /// </summary>
        /// <returns></returns>
        public CommonResult AddRoleUser(AddRoleUserClientInput input)
        {
            var result = new CommonResult();

            using (var trans = _unitOfWorkManager.Begin())
            {
                try
                {
                    var role = _authRepository.Orm.Select<Role>().Where(p => p.Id == input.RoleId).First();
                    if (role == null)
                    {
                        result.IsError = true;
                        result.Message = "角色不存在";
                        result.Value = EnumBaseResult.SystemError;
                        return result;
                    }

                    //获取当前角色用户Id
                    var currentRoleUserIds = _authRepository.Orm.Select<UserRoleRelation>().Where(p => p.RoleId == input.RoleId).ToList(p => p.UserId);

                    //获取添加的用户Id
                    if (input.UserIds == null)
                        input.UserIds = new List<string>();
                    var addUserIds = input.UserIds.Except(currentRoleUserIds);

                    if (addUserIds.Count() > 0)
                    {
                        var addUserRoles = new List<UserRoleRelation>();
                        foreach (var addUserId in addUserIds)
                        {
                            addUserRoles.Add(new UserRoleRelation()
                            {
                                RoleId = input.RoleId,
                                UserId = addUserId
                            });
                        }

                        _authRepository.Orm.Insert<UserRoleRelation>(addUserRoles).ExecuteAffrows();

                        //取消添加的用户的Token
                        /*try
                        {
                            foreach (var addUserId in addUserIds)
                            {
                                this.CancelAuthToken(new CancelAuthTokenInput
                                {
                                    Uid = addUserId,
                                });
                            }
                        }
                        catch (Exception)
                        {
                        }*/
                    }

                    trans.Commit();
                }
                catch
                {
                    trans.Rollback();
                }
            }

            result.IsError = false;
            result.Message = "添加角色用户成功";
            result.Value = EnumBaseResult.OK;
            return result;
        }

        /// <summary>
        /// 删除角色用户
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public CommonResult DelRoleUser(DelRoleUserClientInput input)
        {
            var result = new CommonResult();

            using (var trans = _unitOfWorkManager.Begin())
            {
                try
                {
                    var role = _authRepository.Orm.Select<Role>().Where(p => p.Id == input.RoleId).First();
                    if (role == null)
                    {
                        result.IsError = true;
                        result.Message = "角色不存在";
                        result.Value = EnumBaseResult.SystemError;
                        return result;
                    }

                    //获取删除的用户Id
                    if (input.UserIds == null)
                        input.UserIds = new List<string>();
                    var delUserIds = input.UserIds;

                    if (delUserIds.Count() > 0)
                    {
                        _authRepository.Orm.Delete<UserRoleRelation>().Where(p => p.RoleId == input.RoleId && delUserIds.Contains(p.UserId)).ExecuteAffrows();

                        //取消添加的用户的Token
                        /*try
                        {
                            foreach (var delUserId in delUserIds)
                            {
                                this.CancelAuthToken(new CancelAuthTokenInput
                                {
                                    Uid = delUserId,
                                });
                            }
                        }
                        catch (Exception)
                        {
                        }*/
                    }

                    trans.Commit();
                }
                catch
                {
                    trans.Rollback();
                }
            }

            result.IsError = false;
            result.Message = "删除角色用户成功";
            result.Value = EnumBaseResult.OK;
            return result;
        }

        /// <summary>
        /// 下载角色用户模板
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public CommonResult<ExportDocumentOutPut> DownloadRoleUserTemplate(DownloadRoleUserTemplateClientInput input)
        {
            var result = new CommonResult<ExportDocumentOutPut>();

            HttpWebResponse httpWebResponse = (WebRequest.Create(RoleUserExportTemplateUrl) as HttpWebRequest).GetResponse() as HttpWebResponse;
            MemoryStream memoryStream = null;
            using (Stream stream = httpWebResponse.GetResponseStream())
            {
                byte[] array = new byte[httpWebResponse.ContentLength];
                int num = 0;
                int num2 = 0;
                do
                {
                    num2 = stream.Read(array, num, array.Length - num);
                    num += num2;
                }
                while (num2 > 0);
                memoryStream = new MemoryStream(array);
            }

            result.IsError = false;
            result.Message = "获取成功";
            result.Value = RS.BaseModel.Enum.EnumBaseResult.OK;
            result.Result = new ExportDocumentOutPut()
            {
                FileName = "角色成员导入模板.xlsx",
                MemoryStream = memoryStream
            };

            return result;
        }

        /// <summary>
        /// 导入角色用户
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public CommonResult ImportRoleUser(ImportRoleUserClientInput input)
        {
            var result = new CommonResult();

            using (var file = input.File.OpenReadStream())
            {
                try
                {
                    //获取全部角色
                    var allRoles = _authRepository.Orm.Select<Role>().ToList(p => new
                    {
                        p.Id,
                        p.Name
                    });
                    //获取全部用户
                    var allUsers = _authRepository.Orm.Select<UUIUser>().Where(p => p.JobState == 1).ToList(p => new
                    {
                        p.Id,
                        p.LoginName
                    });

                    var rows = MiniExcel.Query(file, true);
                    //验证数据项,并填充数据
                    int rowIndex = 2;
                    string errorMsg = "";

                    foreach (var row in rows)
                    {
                        List<string> errorMessages = new List<string>();

                        var dic = (IDictionary<string, object?>)(row);
                        if (dic["角色/Role"] == null || string.IsNullOrEmpty(dic["角色/Role"].ToString()))
                        {
                            errorMessages.Add("角色/Role不允许为空");
                        }
                        else
                        {
                            var role = dic["角色/Role"].ToString().Trim();
                            if (!allRoles.Any(p => p.Name == role))
                            {
                                errorMessages.Add("角色/Role不存在");
                            }
                        }

                        if (dic["域账号/LoginName"] == null || string.IsNullOrEmpty(dic["域账号/LoginName"].ToString()))
                        {
                            errorMessages.Add("域账号/LoginName不允许为空");
                        }
                        else
                        {
                            var loginName = dic["域账号/LoginName"].ToString().Trim().ToLower();
                            if (!allUsers.Any(p => p.LoginName != null && p.LoginName.ToLower() == loginName))
                            {
                                errorMessages.Add("在职的域账号/LoginName不存在");
                            }
                        }

                        if (dic["类别/Category"] == null || string.IsNullOrEmpty(dic["类别/Category"].ToString()))
                        {
                            errorMessages.Add("类别/Category不允许为空");
                        }
                        else
                        {
                            var type = dic["类别/Category"].ToString();
                            if (type != "新增" && type != "删除")
                            {
                                errorMessages.Add("类别/Category填写内容不正确");
                            }
                        }

                        if (errorMessages.Count > 0)
                        {
                            errorMsg += $"第{rowIndex}行:{string.Join(",", errorMessages)}\n";
                        }

                        rowIndex++;
                    }

                    if (!string.IsNullOrEmpty(errorMsg))
                    {
                        result.IsError = true;
                        result.Message = errorMsg;
                        result.Value = EnumBaseResult.SystemError;

                        file.Close();

                        return result;
                    }

                    //开始导入数据
                    using (var trans = _unitOfWorkManager.Begin(isolationLevel: IsolationLevel.ReadCommitted))
                    {
                        try
                        {
                            var allRowUserIds = new List<string>();
                            foreach (var row in rows)
                            {
                                var dic = (IDictionary<string, object?>)(row);
                                var roleName = dic["角色/Role"].ToString().Trim();
                                var loginName = dic["域账号/LoginName"].ToString().Trim().ToLower();
                                var type = dic["类别/Category"].ToString().Trim();

                                var roleId = allRoles.Where(p => p.Name == roleName).Select(p => p.Id).First();
                                var userId = allUsers.Where(p => p.LoginName != null && p.LoginName.ToLower() == loginName).Select(p => p.Id).First();

                                if (!allRowUserIds.Any(p => p == userId))
                                {
                                    allRowUserIds.Add(userId);
                                }

                                if (type == "新增")
                                {
                                    if (!_authRepository.Orm.Select<UserRoleRelation>().Any(p => p.RoleId == roleId && p.UserId == userId))
                                    {
                                        _authRepository.Orm.Insert(new UserRoleRelation()
                                        {
                                            RoleId = roleId,
                                            UserId = userId,
                                        }).ExecuteAffrows();
                                    }
                                }
                                else if (type == "删除")
                                {
                                    _authRepository.Orm.Delete<UserRoleRelation>().Where(p => p.RoleId == roleId && p.UserId == userId).ExecuteAffrows();
                                }
                            }

                            /*foreach (var rowUserId in allRowUserIds)
                            {
                                try
                                {
                                    this.CancelAuthToken(new CancelAuthTokenInput
                                    {
                                        Uid = rowUserId,
                                    });
                                }
                                catch (Exception)
                                {
                                }
                            }*/

                            trans.Commit();
                        }
                        catch
                        {
                            trans.Rollback();
                            throw new Exception("导入异常");
                        }
                    }


                    file.Close();
                }
                catch (Exception ex)
                {
                    file.Close();

                    logger.Error(ex.ToString());

                    result.IsError = true;
                    result.Message = "系统异常";
                    result.Value = EnumBaseResult.SystemError;

                    return result;
                };
            }

            result.IsError = false;
            result.Value = EnumBaseResult.OK;
            result.Message = "导入成功";

            return result;
        }

        /// <summary>
        /// 导入角色用户(项目)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public CommonResult ImportProjectRoleUser(ImportRoleUserClientInput input)
        {
            var result = new CommonResult();

            //获取角色关联项目
            var getDictionaryItemProjectsResult = _ltDictionaryClient.GetDictionaryItemProjects(new Lutos.Dictionary.Domain.Integrate.Input.GetDictionaryItemProjectsInput
            {
                UserId = input.Uid
            });
            if (getDictionaryItemProjectsResult == null || getDictionaryItemProjectsResult.IsError)
            {
                result.IsError = true;
                result.Value = RS.BaseModel.Enum.EnumBaseResult.SystemError;
                result.Message = "获取当前用户的项目管理权限失败";
                return result;
            }

            using (var file = input.File.OpenReadStream())
            {
                try
                {
                    //获取全部角色
                    //根据项目获取角色Id

                    var allRoles = _authRepository.Orm.Select<Role, RoleProjectRelation>()
                        .InnerJoin((a, b) => a.Id == b.RoleId && getDictionaryItemProjectsResult.Result.Contains(b.Project))
                        .GroupBy((a, b) => new { a.Id, a.Name })
                        .ToList(p => new
                        {
                            p.Key.Id,
                            p.Key.Name
                        });
                    //获取全部用户
                    var allUsers = _authRepository.Orm.Select<UUIUser>().Where(p => p.JobState == 1).ToList(p => new
                    {
                        p.Id,
                        p.LoginName
                    });

                    var rows = MiniExcel.Query(file, true);
                    //验证数据项,并填充数据
                    int rowIndex = 2;
                    string errorMsg = "";

                    foreach (var row in rows)
                    {
                        List<string> errorMessages = new List<string>();

                        var dic = (IDictionary<string, object?>)(row);
                        if (dic["角色"] == null || string.IsNullOrEmpty(dic["角色"].ToString()))
                        {
                            errorMessages.Add("角色不允许为空");
                        }
                        else
                        {
                            var role = dic["角色"].ToString().Trim();
                            if (!allRoles.Any(p => p.Name == role))
                            {
                                errorMessages.Add("拥有权限的角色不存在");
                            }
                        }

                        if (dic["域账号"] == null || string.IsNullOrEmpty(dic["域账号"].ToString()))
                        {
                            errorMessages.Add("域账号不允许为空");
                        }
                        else
                        {
                            var loginName = dic["域账号"].ToString().Trim().ToLower();
                            if (!allUsers.Any(p => p.LoginName != null && p.LoginName.ToLower() == loginName))
                            {
                                errorMessages.Add("在职的域账号不存在");
                            }
                        }

                        if (dic["类别"] == null || string.IsNullOrEmpty(dic["类别"].ToString()))
                        {
                            errorMessages.Add("类别不允许为空");
                        }
                        else
                        {
                            var type = dic["类别"].ToString();
                            if (type != "新增" && type != "删除")
                            {
                                errorMessages.Add("类别填写内容不正确");
                            }
                        }

                        if (errorMessages.Count > 0)
                        {
                            errorMsg += $"第{rowIndex}行:{string.Join(",", errorMessages)}\n";
                        }

                        rowIndex++;
                    }

                    if (!string.IsNullOrEmpty(errorMsg))
                    {
                        result.IsError = true;
                        result.Message = errorMsg;
                        result.Value = EnumBaseResult.SystemError;

                        file.Close();

                        return result;
                    }

                    //开始导入数据
                    using (var trans = _unitOfWorkManager.Begin(isolationLevel: IsolationLevel.ReadCommitted))
                    {
                        try
                        {
                            var allRowUserIds = new List<string>();
                            foreach (var row in rows)
                            {
                                var dic = (IDictionary<string, object?>)(row);
                                var roleName = dic["角色"].ToString().Trim();
                                var loginName = dic["域账号"].ToString().Trim().ToLower();
                                var type = dic["类别"].ToString().Trim();

                                var roleId = allRoles.Where(p => p.Name == roleName).Select(p => p.Id).First();
                                var userId = allUsers.Where(p => p.LoginName != null && p.LoginName.ToLower() == loginName).Select(p => p.Id).First();

                                if (!allRowUserIds.Any(p => p == userId))
                                {
                                    allRowUserIds.Add(userId);
                                }

                                if (type == "新增")
                                {
                                    if (!_authRepository.Orm.Select<UserRoleRelation>().Any(p => p.RoleId == roleId && p.UserId == userId))
                                    {
                                        _authRepository.Orm.Insert(new UserRoleRelation()
                                        {
                                            RoleId = roleId,
                                            UserId = userId,
                                        }).ExecuteAffrows();
                                    }
                                }
                                else if (type == "删除")
                                {
                                    _authRepository.Orm.Delete<UserRoleRelation>().Where(p => p.RoleId == roleId && p.UserId == userId).ExecuteAffrows();
                                }
                            }

                            /*foreach (var rowUserId in allRowUserIds)
                            {
                                try
                                {
                                    this.CancelAuthToken(new CancelAuthTokenInput
                                    {
                                        Uid = rowUserId,
                                    });
                                }
                                catch (Exception)
                                {
                                }
                            }*/

                            trans.Commit();
                        }
                        catch
                        {
                            trans.Rollback();
                            throw new Exception("导入异常");
                        }
                    }


                    file.Close();
                }
                catch (Exception ex)
                {
                    file.Close();

                    logger.Error(ex.ToString());

                    result.IsError = true;
                    result.Message = "系统异常";
                    result.Value = EnumBaseResult.SystemError;

                    return result;
                };
            }

            result.IsError = false;
            result.Value = EnumBaseResult.OK;
            result.Message = "导入成功";

            return result;
        }

        /// <summary>
        /// 导出用户信息
        /// </summary>
        public class ExportRoleUserInfo
        {
            [ExcelColumnWidth(50)]
            [DisplayName("角色/Role")]
            public string RoleName { get; set; }

            [ExcelColumnWidth(50)]
            [DisplayName("姓名/Name")]
            public string Name { get; set; }

            [ExcelColumnWidth(50)]
            [DisplayName("账号/LoginName")]
            public string LoginName { get; set; }

            [ExcelColumnWidth(50)]
            [DisplayName("邮箱/Email")]
            public string Email { get; set; }

            [ExcelColumnWidth(50)]
            [DisplayName("部门名称/Department")]
            public string Department { get; set; }

            [ExcelColumnWidth(50)]
            [DisplayName("员工类型/EmployeeType")]
            public string EmployeeTypeName { get; set; }

            [ExcelColumnWidth(50)]
            [DisplayName("状态/JobState")]
            public string JobState { get; set; }
        }

        /// <summary>
        /// 导出角色用户
        /// </summary>
        /// <returns></returns>
        public CommonResult<ExportDocumentOutPut> ExportRoleUser(ExportRoleUserClientInput input)
        {
            var result = new CommonResult<ExportDocumentOutPut>();

            long count = 0;

            //获取当前角色
            var role = _authRepository.Orm.Select<Role>().Where(p => p.Id == input.RoleId).First();
            if (role == null)
            {
                result.IsError = true;
                result.Message = "角色不存在";
                result.Value = EnumBaseResult.SystemError;
                return result;
            }

            var infos = this._authRepository.Orm.Select<UUIUser, UserRoleRelation>()
                .InnerJoin((a, b) => a.Id == b.UserId && b.RoleId == input.RoleId)
                .WhereIf(!string.IsNullOrEmpty(input.KeyWord), (a, b) => a.Name.ToLower().Contains(input.KeyWord.ToLower()) || a.LoginName.ToLower().Contains(input.KeyWord.ToLower()))
                .OrderByDescending((a, b) => a.CreateTime)
                .Count(out count)
                .Page(input.Page, input.PageSize)
                .ToList((o, b) => new
                {
                    Name = o.Name,
                    LoginName = o.LoginName,
                    Email = o.Email,
                    Department = o.Department,
                    EmployeeType = o.EmployeeType,
                    JobState = o.JobState
                });

            var values = new List<ExportRoleUserInfo>();
            foreach (var info in infos)
            {
                values.Add(new ExportRoleUserInfo
                {
                    RoleName = role.Name,
                    Name = info.Name,
                    LoginName = info.LoginName,
                    Email = info.Email,
                    Department = info.Department,
                    EmployeeTypeName = GetEmployeeTypeName(info.EmployeeType),
                    JobState = info.JobState == 0 ? "禁用" : info.JobState == 1 ? "启用" : ""
                }); ;
            };

            var memoryStream = new MemoryStream();
            memoryStream.SaveAs(values);
            memoryStream.Seek(0, SeekOrigin.Begin);

            result.IsError = false;
            result.Message = "获取成功";
            result.Value = RS.BaseModel.Enum.EnumBaseResult.OK;
            result.Result = new ExportDocumentOutPut()
            {
                FileName = $"角色用户_{DateTime.UtcNow.AddHours(8).ToString("yyyyMMddHHmmss")}.xlsx",
                MemoryStream = memoryStream
            };

            return result;
        }

        /// <summary>
        /// 获取雇佣类型名称
        /// </summary>
        /// <param name="employeeType"></param>
        /// <returns></returns>
        public string GetEmployeeTypeName(string employeeType)
        {
            switch (employeeType)
            {
                case "0": return "实习";
                case "1": return "正式";
                case "2": return "劳务派遣";
                case "3": return "退休返聘";
                case "4": return "人力外包";
                case "5": return "项目外包";
                case "6": return "合作伙伴";
                case "7": return "供应商";
                case "98": return "供应商（间采）";
                case "99": return "供应商（直采）";
                default: return "";
            }
        }

        /// <summary>
        /// Token交换用户信息
        /// </summary>
        /// <param name="authToken"></param>
        /// <returns></returns>
        [Obsolete]
        public CommonResult<GetUserInfoOutPut> GetUserInfo(string authToken)
        {

            var result = new CommonResult<GetUserInfoOutPut>();

            var user_Token = this.GetUserAuthTokenFromRedis(authToken);

            if (user_Token == null)
            {
                result.Value = EnumBaseResult.InvalidAuthToken;
                return result;
            }

            var userInfo = this.GetUserInfoFromRedis(user_Token.Uid);

            if (userInfo != null)
            {

                result.IsError = false;
                result.Result = userInfo;
                return result;

            }

            var user = this.GetUIUser(user_Token.Uid);

            var auth_type_byte = user_Token.AuthType.Split(',');

            userInfo = new GetUserInfoOutPut();

            foreach (var o in auth_type_byte)
            {

                switch (Enum.Parse(typeof(UUIUserAuthType), o, true))
                {

                    case UUIUserAuthType.auth_base:
                        userInfo.Uid = user.Id;
                        userInfo.Name = user.Name;
                        userInfo.JobNumber = user.JobNumber;
                        userInfo.Avatar = user.Avatar;
                        userInfo.NickName = user.NickName;
                        userInfo.Department = user.Department;
                        userInfo.Title = user.Title;
                        userInfo.Profession = user.Profession;
                        userInfo.JobTitle = user.JobTitle;
                        userInfo.Phone = user.Phone;
                        userInfo.DepartmentId = user.DepartmentId;
                        userInfo.Email = user.Email;
                        userInfo.EmployeeType = user.EmployeeType;
                        userInfo.Gender = user.Gender;
                        userInfo.IdCardNo = user.IdCardNo;
                        userInfo.JobState = user.JobState;
                        userInfo.Nation = user.Nation;
                        userInfo.Nationality = user.Nationality;
                        userInfo.NationalityCode = user.NationalityCode;
                        userInfo.NationPlace = user.NationPlace;
                        userInfo.TopQualifications = user.TopQualifications;
                        userInfo.FeiShuUid = user.FeiShuUid;
                        userInfo.Company = user.Company;
                        userInfo.LoginName = user.LoginName;
                        break;

                    case UUIUserAuthType.auth_info:
                        userInfo.Uid = user.Id;
                        userInfo.Name = user.Name;
                        userInfo.JobNumber = user.JobNumber;
                        userInfo.Avatar = user.Avatar;
                        userInfo.NickName = user.NickName;
                        userInfo.Department = user.Department;
                        userInfo.Title = user.Title;
                        userInfo.Profession = user.Profession;
                        userInfo.JobTitle = user.JobTitle;
                        user.Phone = user.Phone;
                        userInfo.DepartmentId = user.DepartmentId;
                        userInfo.Email = user.Email;
                        userInfo.EmployeeType = user.EmployeeType;
                        userInfo.Gender = user.Gender;
                        userInfo.IdCardNo = user.IdCardNo;
                        userInfo.JobState = user.JobState;
                        userInfo.Nation = user.Nation;
                        userInfo.Nationality = user.Nationality;
                        userInfo.NationalityCode = user.NationalityCode;
                        userInfo.NationPlace = user.NationPlace;
                        userInfo.TopQualifications = user.TopQualifications;
                        userInfo.FeiShuUid = user.FeiShuUid;
                        userInfo.Company = user.Company;
                        userInfo.LoginName = user.LoginName;
                        break;
                }
            }


            var roles = this._authRepository.Orm.Select<UserRoleRelation>().Where(o => o.UserId == user.Id).ToList(o => o.RoleId);

            var actions = this._authRepository.Orm.Select<DTO.Role.Action, RoleActionRelation>().LeftJoin((o, p) => o.Id == p.ActionId).Where((o, p) => roles.Contains(p.RoleId)).ToList();

            userInfo.Actions = actions;

            this.SetUserInfoInRedis(userInfo);

            result.IsError = false;

            result.Result = userInfo;

            return result;
        }


        public CommonResult<GetUserInfoOutPut> GetUserInfoByMobile(string mobile)
        {

            var result = new CommonResult<GetUserInfoOutPut>();


            var user = this._authRepository.Orm.Select<UUIUser>().Where(x => x.Phone == mobile).ToOne();

            if (user == null)
            {

                result.Value = EnumBaseResult.NoResource;
                result.Message = "用户不存在";
                return result;

            }

            var userInfo = new GetUserInfoOutPut();
            userInfo.Uid = user.Id;
            userInfo.Name = user.Name;
            userInfo.JobNumber = user.JobNumber;
            userInfo.Avatar = user.Avatar;
            userInfo.NickName = user.NickName;
            userInfo.Department = user.Department;
            userInfo.Title = user.Title;
            userInfo.Profession = user.Profession;
            userInfo.JobTitle = user.JobTitle;
            user.Phone = user.Phone;
            userInfo.DepartmentId = user.DepartmentId;
            userInfo.Email = user.Email;
            userInfo.EmployeeType = user.EmployeeType;
            userInfo.Gender = user.Gender;
            userInfo.IdCardNo = user.IdCardNo;
            userInfo.JobState = user.JobState;
            userInfo.Nation = user.Nation;
            userInfo.Nationality = user.Nationality;
            userInfo.NationalityCode = user.NationalityCode;
            userInfo.NationPlace = user.NationPlace;
            userInfo.TopQualifications = user.TopQualifications;
            userInfo.FeiShuUid = user.FeiShuUid;
            userInfo.Company = user.Company;
            userInfo.LoginName = user.LoginName;

            result.IsError = false;

            result.Result = userInfo;

            return result;

        }


        public UUIUserAuthCode GetUUIUserAuthCode(string id)
        {
            return this._authRepository.Orm.Select<UUIUserAuthCode>(new { Id = id }).ToOne();
        }
        public List<Role> GetRoles(int pagenum, int pagesize, string condition, string orderby, out long count, object para = null)
        {
            var info = this._authRepository.Orm.Select<Role>().Where(condition, para).OrderBy(orderby).Count(out count).Page(pagenum, pagesize).ToList();
            return info;
        }

        /// <summary>
        /// 获取角色项目关联列表
        /// </summary>
        /// <param name="roleIds">角色Id列表s</param>
        /// <returns></returns>
        public List<RoleProjectRelation> GetRoleProjectRelations(List<string> roleIds)
        {
            var info = this._authRepository.Orm.Select<RoleProjectRelation>().Where(p => roleIds.Contains(p.RoleId)).ToList();
            return info;
        }

        /// <summary>
        /// 保存角色项目关联列表
        /// </summary>
        /// <param name="roleIds">角色Id列表s</param>
        /// <returns></returns>
        public CommonResult SaveRoleProjectRelations(SaveRoleRelateProjectClientInput input)
        {
            CommonResult reuslt = new CommonResult();

            using (var trans = _unitOfWorkManager.Begin())
            {
                try
                {
                    var role = this._authRepository.Orm.Select<Role>().Where(p => p.Id == input.RoleId).First();
                    if (role == null)
                    {
                        reuslt.IsError = true;
                        reuslt.Value = EnumBaseResult.SystemError;
                        reuslt.Message = "角色不存在";

                        return reuslt;
                    }

                    var currentProjects = this._authRepository.Orm.Select<RoleProjectRelation>().Where(p => p.RoleId == input.RoleId).ToList(p => p.Project);

                    var projects = input.Projects;
                    if (projects == null)
                        projects = new List<string>();

                    var addProjects = projects.Except(currentProjects);
                    var delProjects = currentProjects.Except(projects);

                    var addRoleProjectRelations = new List<RoleProjectRelation>();
                    foreach (var addProject in addProjects)
                    {
                        addRoleProjectRelations.Add(new RoleProjectRelation()
                        {
                            Project = addProject,
                            RoleId = input.RoleId,
                        });
                    }

                    this._authRepository.Orm.Insert(addRoleProjectRelations).ExecuteAffrows(); ;
                    this._authRepository.Orm.Delete<RoleProjectRelation>().Where(p => p.RoleId == input.RoleId && delProjects.Contains(p.Project)).ExecuteAffrows();

                    trans.Commit();
                }
                catch
                {
                    trans.Rollback();
                    throw new Exception("保存异常");
                }
            }

            reuslt.IsError = false;
            reuslt.Value = EnumBaseResult.OK;
            reuslt.Message = "保存成功";

            return reuslt;
        }

        [Obsolete]
        public IEnumerable<UUIUser> GetUsers(int pagenum, int pagesize, string condition, string orderby, out long count, object para = null)
        {
            var info = this._authRepository.Orm.Select<UUIUser>().Where(condition, para).OrderBy(orderby).Count(out count).Page(pagenum, pagesize).ToList();
            return info;
        }
        public int UpdateUIUser(UUIUser model)
        {
            var r = this._authRepository.Orm.Update<UUIUser>().SetSource(model).ExecuteAffrows();

            this.CancelAuthToken(new CancelAuthTokenInput
            {

                Uid = model.Id
            });

            return r;
        }
        public int AddUUIUser(UUIUser model)
        {

            using (var trans = _unitOfWorkManager.Begin())
            {


                this._authRepository.Orm.Insert(model).ExecuteAffrows();

                var userRoleRelation = new UserRoleRelation
                {
                    UserId = model.Id
                };

                //添加一个供应商角色
                if (model.EmployeeType == "99" || model.EmployeeType == "98" || model.EmployeeType == "7")
                {
                    userRoleRelation.RoleId = "99";
                }
                else
                {
                    userRoleRelation.RoleId = "0";
                }

                this._authRepository.Orm.Insert(userRoleRelation).ExecuteAffrows();


                trans.Commit();

            }

            return 1;


        }


        public CommonResult AddOrUpdateUser(List<AddOrUpdateUserInput> inputList)
        {

            var successCount = 0;
            var result = new CommonResult();

            foreach (var o in inputList)
            {

                var temp = _authRepository.Orm.Select<UUIUser>().Where(p => p.Id == o.Id).ToOne();

                if (temp != null)
                {
                    temp.Name = o.Name;
                    // temp.Avatar = o.Picture;
                    temp.Phone = o.Phone;
                    temp.JobNumber = o.JobNumber;
                    temp.LoginName = o.LoginName;
                    temp.NickName = o.NickName;
                    temp.Company = o.Company;
                    temp.CompanyNo = o.CompanyNo;
                    //temp.Department = o.Department;
                    temp.DepartmentId = o.DepartmentId;
                    temp.JobTitle = o.JobTitle;
                    temp.Title = o.Title;
                    temp.Profession = o.Profession;
                    temp.FeiShuUid = o.FSUnionId;
                    temp.ExtFeiShuUid = o.ExtFSUnionId;
                    temp.Email = o.Email;
                    temp.IdCardNo = o.IdCardNo;
                    temp.Nationality = o.Nationality;
                    temp.NationalityCode = o.NationalityCode;
                    temp.Nationality = o.Nationality;
                    temp.Gender = o.Gender;
                    temp.JobState = o.JobState;
                    temp.TopQualifications = o.TopQualifications;
                    temp.Nation = o.Nation;
                    temp.NationPlace = o.NationPlace;
                    temp.EmployeeType = o.EmployeeType;
                    temp.CompanyAge = o.CompanyAge;
                    temp.PositionName = o.PositionName;
                    temp.JobLevel = o.JobLevel;
                    temp.StaffSystem = o.StaffSystem;
                    temp.StaffSystemCode = o.StaffSystemCode;
                    temp.BirthDate = o.BirthDate;
                    temp.Managerid = o.Managerid;

                    var temp_r = _authRepository.Orm.Update<UUIUser>().SetSource(temp).ExecuteAffrows();

                    if (temp_r > 0)
                    {

                        successCount++;
                    }

                }
                else
                {

                    var user = new UUIUser();
                    Console.WriteLine("用户Id1:" + o.Id);
                    user.Id = o.Id;
                    user.Name = o.Name;
                    user.Avatar = o.Picture;
                    user.Phone = o.Phone;
                    user.JobNumber = o.JobNumber;
                    user.LoginName = o.LoginName;
                    user.NickName = o.NickName;
                    user.Company = o.Company;
                    user.CompanyNo = o.CompanyNo;
                    user.Managerid = o.Managerid;
                    //user.Department = o.Department;
                    user.DepartmentId = o.DepartmentId;
                    user.JobTitle = o.JobTitle;
                    user.Title = o.Title;
                    user.Profession = o.Profession;
                    user.FeiShuUid = o.FSUnionId;
                    user.ExtFeiShuUid = o.ExtFSUnionId;
                    user.Email = o.Email;
                    user.IdCardNo = o.IdCardNo;
                    user.Nationality = o.Nationality;
                    user.NationalityCode = o.NationalityCode;
                    user.Nationality = o.Nationality;
                    user.Gender = o.Gender;
                    user.JobState = o.JobState;
                    user.TopQualifications = o.TopQualifications;
                    user.Nation = o.Nation;
                    user.NationPlace = o.NationPlace;
                    user.EmployeeType = o.EmployeeType;
                    user.CompanyAge = o.CompanyAge;
                    user.PositionName = o.PositionName;
                    user.JobLevel = o.JobLevel;
                    user.StaffSystem = o.StaffSystem;
                    user.StaffSystemCode = o.StaffSystemCode;
                    user.BirthDate = o.BirthDate;
                    user.PassWord = SecretHelper.GetMD5(user.Phone);

                    var temp_r = this.AddUUIUser(user);

                    //给用户设置一个默认角色

                    if (temp_r > 0)
                    {

                        successCount++;
                    }
                }

            }

            result.IsError = false;
            result.Message = $"共{inputList.Count}个；处理{successCount}个";

            return result;

        }


        public Role GetRole(string id)
        {
            return this._authRepository.Orm.Select<Role>(new { Id = id }).ToOne();
        }

        public List<ActionGroup> GetActionGroup()
        {

            var info = new ActionGroup
            {
                Id = "0",
                Status = 1,
                Weight = 1,
                Name = "应用权限"
            };

            var info2 = new ActionGroup
            {
                Id = "2",
                Status = 1,
                Weight = 1,
                Name = "页面权限"
            };

            var info3 = new ActionGroup
            {

                Id = "3",
                Status = 1,
                Weight = 1,
                Name = "密级权限"

            };

            var info4 = new ActionGroup
            {

                Id = "4",
                Status = 1,
                Weight = 1,
                Name = "知识中心项目可见权限"

            };

            var info5 = new ActionGroup
            {

                Id = "5",
                Status = 1,
                Weight = 1,
                Name = "知识中心管理"
            };

            var info6 = new ActionGroup
            {

                Id = "6",
                Status = 1,
                Weight = 1,
                Name = "Interface管理"
            };

            var info7 = new ActionGroup
            {

                Id = "7",
                Status = 1,
                Weight = 1,
                Name = "法规校核管理"
            };

            var info8 = new ActionGroup
            {

                Id = "8",
                Status = 1,
                Weight = 1,
                Name = "SVDS"
            };

            var info9 = new ActionGroup
            {

                Id = "9",
                Status = 1,
                Weight = 1,
                Name = "模板管理"
            };
            var info10 = new ActionGroup
            {

                Id = "10",
                Status = 1,
                Weight = 1,
                Name = "零部件清单管理"
            };
            var info11 = new ActionGroup
            {

                Id = "11",
                Status = 1,
                Weight = 1,
                Name = "文档任务中心管理"
            };
            var info12 = new ActionGroup
            {

                Id = "12",
                Status = 1,
                Weight = 1,
                Name = "评审中心管理"
            };
            var info13 = new ActionGroup
            {

                Id = "13",
                Status = 1,
                Weight = 1,
                Name = "案例管理"
            };
            var info14 = new ActionGroup
            {

                Id = "14",
                Status = 1,
                Weight = 1,
                Name = "标准管理"
            };
            var info15 = new ActionGroup
            {

                Id = "15",
                Status = 1,
                Weight = 1,
                Name = "技术文件发放管理"
            };
            var info16 = new ActionGroup
            {

                Id = "16",
                Status = 1,
                Weight = 1,
                Name = "签字盖章页管理"
            };
            var info17 = new ActionGroup
            {

                Id = "17",
                Status = 1,
                Weight = 1,
                Name = "项目部门UPL可见权限"
            };
            var info18 = new ActionGroup
            {

                Id = "18",
                Status = 1,
                Weight = 1,
                Name = "部门UPL可见权限"
            };

            var actions = this._authRepository.Orm.Select<ApplicationModel>().ToList<DTO.Role.Action>(o => new DTO.Role.Action
            {
                Id = o.Id,
                Description = o.Name,
                Status = 1,
                ActionName = o.Name,
                Type = 2

            }).ToList();


            var actions2 = this._authRepository.Orm.Select<DTO.Role.Action>().Where(o => o.Type == 0).ToList();
            var actions3 = this._authRepository.Orm.Select<DTO.Role.Action>().Where(o => o.Type == 3).ToList();
            var actions4 = this._authRepository.Orm.Select<DTO.Role.Action>().Where(o => o.Type == 4).ToList();
            var actions5 = this._authRepository.Orm.Select<DTO.Role.Action>().Where(o => o.Type == 5).ToList();
            var actions6 = this._authRepository.Orm.Select<DTO.Role.Action>().Where(o => o.Type == 6).ToList();
            var actions7 = this._authRepository.Orm.Select<DTO.Role.Action>().Where(o => o.Type == 7).ToList();
            var actions8 = this._authRepository.Orm.Select<DTO.Role.Action>().Where(o => o.Type == 8).ToList();
            var actions9 = this._authRepository.Orm.Select<DTO.Role.Action>().Where(o => o.Type == 9).ToList();
            var actions10 = this._authRepository.Orm.Select<DTO.Role.Action>().Where(o => o.Type == 10).ToList();
            var actions11 = this._authRepository.Orm.Select<DTO.Role.Action>().Where(o => o.Type == 11).ToList();
            var actions12 = this._authRepository.Orm.Select<DTO.Role.Action>().Where(o => o.Type == 12).ToList();
            var actions13 = this._authRepository.Orm.Select<DTO.Role.Action>().Where(o => o.Type == 13).ToList();
            var actions14 = this._authRepository.Orm.Select<DTO.Role.Action>().Where(o => o.Type == 14).ToList();
            var actions15 = this._authRepository.Orm.Select<DTO.Role.Action>().Where(o => o.Type == 15).ToList();
            var actions16 = this._authRepository.Orm.Select<DTO.Role.Action>().Where(o => o.Type == 16).ToList();
            var actions17 = this._authRepository.Orm.Select<DTO.Role.Action>().Where(o => o.Type == 17).ToList();
            var actions18 = this._authRepository.Orm.Select<DTO.Role.Action>().Where(o => o.Type == 18).ToList();

            info.Actions = actions;

            info2.Actions = actions2;

            info3.Actions = actions3;

            info4.Actions = actions4;

            info5.Actions = actions5;

            info6.Actions = actions6;

            info7.Actions = actions7;

            info8.Actions = actions8;

            info9.Actions = actions9;
            info10.Actions = actions10;
            info11.Actions = actions11;
            info12.Actions = actions12;
            info13.Actions = actions13;
            info14.Actions = actions14;
            info15.Actions = actions15;
            info16.Actions = actions16;
            info17.Actions = actions17;
            info18.Actions = actions18;

            return new List<ActionGroup>
            {
                info,
                info2,
                info3,
                info4,
                info5,
                info6,
                info7,
                info8,
                info9,
                info10,
                info11,
                info12,
                info13,
                info14,
                info15,
                info16,
                info17,
                info18,
            };
        }

        public int UpdateRoleAction(Role Role, List<string> Actions)
        {
            var r = 0;
            using (var trans = _unitOfWorkManager.Begin())
            {

                try
                {
                    if (_authRepository.Orm.Select<Role>().Any(p => p.Id != Role.Id && p.Name == Role.Name))
                    {
                        return -2;
                    }

                    r += _authRepository.Orm.Update<Role>().SetSource(Role).ExecuteAffrows();

                    r += _authRepository.Orm.Delete<RoleActionRelation>(new { RoleId = Role.Id }).ExecuteAffrows();

                    var newCJWRoleActonRelation = Actions.Select(o => new RoleActionRelation
                    {
                        RoleId = Role.Id,
                        ActionId = o


                    }).ToList();

                    r += _authRepository.Orm.Insert<RoleActionRelation>(newCJWRoleActonRelation).ExecuteAffrows();

                    //取消所有被该角色影响的用户的token

                    /*var userRole = this._authRepository.Orm.Select<UserRoleRelation>().Where(o => o.RoleId == Role.Id).ToList(o => o.UserId).ToList();

                    foreach (var o in userRole)
                    {

                        this.CancelAuthToken(new CancelAuthTokenInput
                        {
                            Uid = o
                        });

                    }*/
                }
                catch
                {

                    trans.Rollback();
                }


            }
            return r;


        }

        public int CreateRoleAction(Role Role, List<string> Actions)
        {

            var r = 0;
            using (var trans = _unitOfWorkManager.Begin())
            {
                try
                {
                    if (_authRepository.Orm.Select<Role>().Any(p => p.Name == Role.Name))
                    {
                        return -2;
                    }

                    r += _authRepository.Orm.Insert<Role>(Role).ExecuteAffrows();

                    var newCJWRoleActonRelation = Actions.Select(o => new RoleActionRelation
                    {
                        RoleId = Role.Id,
                        ActionId = o


                    }).ToList();

                    r += _authRepository.Orm.Insert<RoleActionRelation>(newCJWRoleActonRelation).ExecuteAffrows();

                }
                catch
                {
                    trans.Rollback();
                }
            }
            return r;


        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="roleId">角色Id</param>
        /// <returns></returns>
        public CommonResult DelRole(string? roleId)
        {
            CommonResult result = new CommonResult();

            if (UnDelRoleIds.Contains(roleId))
            {
                result.IsError = true;
                result.Message = "该角色不允许被删除";
                result.Value = EnumBaseResult.SystemError;
                return result;
            }

            using (var trans = _unitOfWorkManager.Begin())
            {
                try
                {
                    if (!_authRepository.Orm.Select<Role>().Any(p => p.Id == roleId))
                    {
                        result.IsError = true;
                        result.Message = "角色不存在";
                        result.Value = EnumBaseResult.SystemError;
                        return result;
                    }

                    //获取当前角色所有用户Id
                    var userIds = _authRepository.Orm.Select<UserRoleRelation>().Where(p => p.RoleId == roleId).ToList(p => p.UserId);

                    _authRepository.Orm.Delete<Role>().Where(p => p.Id == roleId).ExecuteAffrows();
                    _authRepository.Orm.Delete<RoleActionRelation>().Where(p => p.RoleId == roleId).ExecuteAffrows();
                    _authRepository.Orm.Delete<RoleProjectRelation>().Where(p => p.RoleId == roleId).ExecuteAffrows();
                    _authRepository.Orm.Delete<UserRoleRelation>().Where(p => p.RoleId == roleId).ExecuteAffrows();

                    /*try
                    {
                        foreach (var userId in userIds)
                        {
                            this.CancelAuthToken(new CancelAuthTokenInput
                            {
                                Uid = userId
                            });
                        }
                    }
                    catch (Exception)
                    { 
                    }*/


                    trans.Commit();
                }
                catch
                {
                    trans.Rollback();
                }
            }

            result.IsError = false;
            result.Message = "删除成功";
            result.Value = EnumBaseResult.OK;
            return result;
        }

        public List<string> GetRoleAction(string RoleId)
        {
            var info = _authRepository.Orm.Select<RoleActionRelation>(new { RoleId = RoleId }).ToList(o => o.ActionId);
            return info;
        }

        public List<string> GetRoleProject(string RoleId)
        {
            var info = _authRepository.Orm.Select<RoleProjectRelation>(new { RoleId = RoleId }).ToList(o => o.Project);
            return info;
        }

        public int CreateUser(UUIUser user, List<string> Roles)
        {

            var r = 0;
            using (var trans = _unitOfWorkManager.Begin())
            {
                try
                {
                    r += _authRepository.Orm.Insert<UUIUser>(user).ExecuteAffrows();

                    var UserRoleRelation = Roles.Select(o => new UserRoleRelation
                    {
                        UserId = user.Id,
                        RoleId = o

                    }).ToList();

                    r += _authRepository.Orm.Insert<UserRoleRelation>(UserRoleRelation).ExecuteAffrows();

                }
                catch
                {
                    trans.Rollback();
                }
            }
            return r;


        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="user"></param>
        /// <param name="Roles"></param>
        /// <returns></returns>
        public int UpdateUserRole(UUIUser user, List<string> Roles)
        {

            var r = 0;

            using (var trans = _unitOfWorkManager.Begin())
            {
                try
                {
                    r += _authRepository.Orm.Update<UUIUser>(user).ExecuteAffrows();

                    r += _authRepository.Orm.Delete<UserRoleRelation>().Where(o => o.UserId == user.Id).ExecuteAffrows();

                    if (Roles.Count() > 0)
                    {
                        var UserRoleRelation = Roles.Select(o => new UserRoleRelation
                        {
                            UserId = user.Id,
                            RoleId = o

                        }).ToList();

                        r += _authRepository.Orm.Insert<UserRoleRelation>(UserRoleRelation).ExecuteAffrows();
                    }

                    //取消所有token

                    this.CancelAuthToken(new CancelAuthTokenInput
                    {
                        Uid = user.Id,
                    });
                }
                catch
                {
                    trans.Rollback();
                }
            }

            return r;

        }

        public CommonResult UpdateKnowledgeReadAction(UpdateKnowledgeReadActionInput input)
        {
            CommonResult result = new CommonResult();

            //新增
            if (input.Type == 0)
            {
                if (!_authRepository.Orm.Select<DTO.Role.Action>().Any(p => p.Type == 4 && p.ActionName == input.OriActionName))
                {
                    var action = new DTO.Role.Action()
                    {
                        ActionName = input.ActionName,
                        Type = 4,
                        Description = input.Description,
                        Status = 1
                    };

                    _authRepository.Orm.Insert<DTO.Role.Action>(action).ExecuteAffrows();
                }
                if (!_authRepository.Orm.Select<DTO.Role.Action>().Any(p => p.Type == 17 && p.ActionName == input.OriActionName))
                {
                    var action = new DTO.Role.Action()
                    {
                        ActionName = input.ActionName,
                        Type = 17,
                        Description = input.Description,
                        Status = 1
                    };

                    _authRepository.Orm.Insert<DTO.Role.Action>(action).ExecuteAffrows();
                }
            }
            //更新
            else if (input.Type == 1)
            {
                _authRepository.Orm.Update<DTO.Role.Action>()
                    .Set(p => p.ActionName, input.ActionName)
                    .Set(p => p.Description, input.Description)
                    .Where(p => p.Type == 4 && p.ActionName == input.OriActionName)
                    .ExecuteAffrows();
                _authRepository.Orm.Update<DTO.Role.Action>()
                    .Set(p => p.ActionName, input.ActionName)
                    .Set(p => p.Description, input.Description)
                    .Where(p => p.Type == 17 && p.ActionName == input.OriActionName)
                    .ExecuteAffrows();
            }
            //删除
            else if (input.Type == 2)
            {
                _authRepository.Orm.Delete<DTO.Role.Action>()
                    .Where(p => p.Type == 4 && p.ActionName == input.ActionName)
                    .ExecuteAffrows();
                _authRepository.Orm.Delete<DTO.Role.Action>()
                    .Where(p => p.Type == 17 && p.ActionName == input.ActionName)
                    .ExecuteAffrows();
            }

            result.IsError = false;
            result.Message = "更新成功";
            result.Value = EnumBaseResult.OK;

            return result;
        }


        #region 登录
        public CommonResult<BaseUserLoginModel> Login(string LoginName, string PassWord, string CodeToken, string VerifyCode)
        {

            var result = new CommonResult<BaseUserLoginModel>();

            if (string.IsNullOrEmpty(VerifyCode))
            {
                result.Message = "验证码不能为空";

                return result;
            }
            if (string.IsNullOrEmpty(LoginName))
            {
                result.Message = "用户名不能为空";

                return result;

            }
            if (string.IsNullOrEmpty(PassWord))
            {
                result.Message = "密码不能为空";

                return result;
            }

            var code = UserAuthRedis.Get($"VerifyCode:{CodeToken}");
            if (string.IsNullOrEmpty(code))
            {
                result.Message = "验证码已过期，请刷新页面";

                return result;
            }

            if (VerifyCode.ToLower().Trim() != code.ToLower().Trim())
            {
                result.Message = "验证码不正确，请重试";

                return result;
            }

            UserAuthRedis.Del($"VerifyCode:{CodeToken}");

            var pw = SecretHelper.GetMD5(PassWord);

            object obj = null;

            if (RegHelper.CheckNum(LoginName))
            {

                if (LoginName.Length == 11)
                {
                    obj = new { Phone = LoginName, PassWord = pw };
                }
                else if (LoginName.Length == 6)
                {
                    obj = new { JobNumber = LoginName, PassWord = pw };
                }
                else
                {
                    obj = new { LoginName = LoginName, PassWord = pw };
                }
            }
            else
            {
                obj = new { LoginName = LoginName, PassWord = pw };
            }


            var user = this.GetUIUser(obj);


            if (user == null)
            {
                result.Message = "用户名或密码错误";

                return result;

            }


            var UUIUserAuthToken = new UUIUserAuthToken
            {
                Uid = user.Id,
                UserUniqueId = user.UniqueId,
                AuthType = "auth_base",
                AppId = ConfigurationHelper.GetAppSettings("AppId"),
                AuthCode = "0"
            };
            UUIUserAuthToken.SetAuthToken();

            var GeUserAuthTokenOutput = new GetUserAuthTokenOutput
            {
                ExpireTime = UUIUserAuthToken.ExpireTime,
                AuthToken = UUIUserAuthToken.AuthToken
            };


            this.SetUserAuthTokenInRedis(UUIUserAuthToken);


            var login_user_model = new BaseUserLoginModel
            {
                Id = UUIUserAuthToken.Uid,
                Name = user.Name,
                Token = UUIUserAuthToken.AuthToken,
            };

            result.IsError = false;
            result.Result = login_user_model;

            return result;



        }

        /// <summary>
        /// 检查用户authtoken是否有效
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="authToken"></param>
        /// <returns></returns>
        public CommonResult CheckUserAuth(string authToken)
        {

            var result = new CommonResult();

            var userAuthToken = this.GetUserAuthTokenFromRedis(authToken);

            if (userAuthToken == null)
            {

                result.Value = EnumBaseResult.InvalidAuthToken;

                return result;
            }

            return result;
        }

        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <returns></returns>
        public async Task<CommonResult<GetVerifyCodeOutPut>> GetVerifyCode()
        {
            CommonResult<GetVerifyCodeOutPut> commonResult = new();
            var codeToken = IdHelper.GetId();
            var code = await VerifyCodeHelper.GetCodeAsync(4);

            UserAuthRedis.Set($"VerifyCode:{codeToken}", code, 120);

            commonResult.Result = new GetVerifyCodeOutPut
            {
                CodeToken = codeToken,
                ImgCode = "data:image/png;base64," + Convert.ToBase64String(await VerifyCodeHelper.GenerateCaptchaImageAsync(code, 80, 40))
            };

            commonResult.IsError = false;
            commonResult.Message = "获取成功";

            return commonResult;
        }

        #endregion


        #region 组织

        public CommonResult AddOrUpdateOrg(List<AddOrUpdateOrgInput> inputList)
        {

            var successCount = 0;
            var result = new CommonResult();

            foreach (var o in inputList)
            {

                var temp = _authRepository.Orm.Select<Organization>().Where(p => p.Id == o.Id).ToOne();

                if (temp != null)
                {
                    bool isChange = false;
                    if (temp.OrgName != o.OrgName)
                    {
                        isChange = true;
                    }

                    temp.OrgName = o.OrgName;
                    temp.EnName = o.EnName;
                    temp.FullName = o.FullName;
                    temp.ParentId = o.ParentId;
                    temp.Type = o.Type;
                    temp.State = o.State;
                    temp.Sapcode = o.Sapcode;
                    temp.CostCenter = o.CostCenter;
                    temp.CostCenterCode = o.CostCenterCode;
                    temp.WechatId = o.WechatId;
                    temp.FSOrgId = o.FSOrgId;
                    temp.FSOrgChatId = o.FSOrgChatId;
                    temp.OrgManger = o.OrgManger;
                    temp.OrgMangeraCode = o.OrgMangeraCode;
                    temp.EffectiveTime = o.EffectiveTime;
                    temp.ExpirationTime = o.ExpirationTime;
                    temp.Level = o.Level;
                    temp.Property = o.Property;

                    var temp_r = _authRepository.Orm.Update<Organization>().SetSource(temp).ExecuteAffrows();

                    if (temp_r > 0)
                    {
                        successCount++;
                    }

                    if (isChange)
                    {
                        _authRepository.Orm.Update<UUIUser>().Set(p => p.Department, o.OrgName).Where(p => p.DepartmentId == o.Id).ExecuteAffrows();
                    }
                }
                else
                {

                    var model = new Organization();
                    model.Id = o.Id;
                    model.OrgName = o.OrgName;
                    model.EnName = o.EnName;
                    model.FullName = o.FullName;
                    model.ParentId = o.ParentId;
                    model.Type = o.Type;
                    model.State = o.State;
                    model.Sapcode = o.Sapcode;
                    model.CostCenter = o.CostCenter;
                    model.CostCenterCode = o.CostCenterCode;
                    model.WechatId = o.WechatId;
                    model.FSOrgId = o.FSOrgId;
                    model.FSOrgChatId = o.FSOrgChatId;
                    model.OrgManger = o.OrgManger;
                    model.OrgMangeraCode = o.OrgMangeraCode;
                    model.EffectiveTime = o.EffectiveTime;
                    model.ExpirationTime = o.ExpirationTime;
                    model.Level = o.Level;
                    model.Property = o.Property;

                    var temp_r = _authRepository.Orm.Insert(model).ExecuteAffrows();

                    if (temp_r > 0)
                    {

                        successCount++;
                    }

                    _authRepository.Orm.Update<UUIUser>().Set(p => p.Department, o.OrgName).Where(p => p.DepartmentId == o.Id).ExecuteAffrows();
                }

            }

            result.IsError = false;

            result.Message = $"共{inputList.Count}个；处理{successCount}个";

            return result;

        }

        /// <summary>
        /// 获取组织列表
        /// </summary>
        /// <returns></returns>
        public CommonResult<List<Organization>> GetOrgList()
        {
            CommonResult<List<Organization>> result = new CommonResult<List<Organization>>();

            result.Result = _authRepository.Orm.Select<Organization>().ToList();

            result.IsError = false;
            result.Value = EnumBaseResult.OK;
            result.Message = "获取成功";

            return result;
        }

        /// <summary>
        /// 获取组织树列表
        /// </summary>
        /// <returns></returns>
        public CommonResult<List<OrgTreeOutPut>> GetOrgTreeList()
        {
            CommonResult<List<OrgTreeOutPut>> result = new CommonResult<List<OrgTreeOutPut>>();

            var orgs = _authRepository.Orm.Select<Organization>().Where(m => m.State == DTO.Org.Enum.EnumOrgState.valid).ToList();

            result.Result = BuildOrgTree(orgs, "0");

            result.IsError = false;
            result.Value = EnumBaseResult.OK;
            result.Message = "获取成功";

            return result;
        }

        /// <summary>
        /// 构造组织树结构
        /// </summary>
        /// <param name="infos">组织信息列表</param>
        /// <param name="parentId">父节点Id</param>
        /// <returns></returns>
        public List<OrgTreeOutPut> BuildOrgTree(List<Organization> infos, string? parentId)
        {
            List<OrgTreeOutPut> orgTreeOutPuts = new List<OrgTreeOutPut>();
            var orgs = infos.Where(p => p.ParentId == parentId).ToList();
            foreach (var org in orgs)
            {
                orgTreeOutPuts.Add(new OrgTreeOutPut
                {
                    Id = org.Id,
                    ParentId = org.ParentId,
                    EnName = org.EnName,
                    FullName = org.FullName,
                    Level = org.Level,
                    OrgName = org.OrgName,
                    Children = BuildOrgTree(infos, org.Id)
                });
            }

            return orgTreeOutPuts;
        }

        /// <summary>
        /// 获取组织用户树列表
        /// </summary>
        /// <returns></returns>
        public CommonResult<List<OrgUserTreeOutPut>> GetOrgUserTreeOutList(GetOrgUserTreeListInput input)
        {
            CommonResult<List<OrgUserTreeOutPut>> result = new CommonResult<List<OrgUserTreeOutPut>>();

            var orgs = _authRepository.Orm.Select<Organization>().ToList(p => new Organization
            {
                Id = p.Id,
                OrgName = p.OrgName,
                EnName = p.EnName,
                FullName = p.FullName,
                ParentId = p.ParentId
            });

            var users = _authRepository.Orm.Select<UUIUser>()
                .WhereIf(input.IsHideJobState != null && input.IsHideJobState == true, p => p.JobState == 1).ToList(p => new UUIUser
                {
                    Id = p.Id,
                    Name = p.Name,
                    LoginName = p.LoginName,
                    DepartmentId = p.DepartmentId
                });

            result.Result = BuildOrgUserTree(orgs, users, "0");

            result.IsError = false;
            result.Value = EnumBaseResult.OK;
            result.Message = "获取成功";

            return result;
        }

        /// <summary>
        /// 构造组织用户树结构
        /// </summary>
        /// <param name="orgs">组织信息列表</param>
        /// <param name="users">用户信息列表</param>
        /// <param name="parentId">父节点Id</param>
        /// <returns></returns>
        public List<OrgUserTreeOutPut> BuildOrgUserTree(List<Organization> orgs, List<UUIUser> users, string? parentId)
        {
            List<OrgUserTreeOutPut> orgUserTreeOutPuts = new List<OrgUserTreeOutPut>();
            var orgs2 = orgs.Where(p => p.ParentId == parentId).ToList();
            foreach (var org in orgs2)
            {
                var orgUserTreeOutPut = new OrgUserTreeOutPut
                {
                    Id = org.Id,
                    ParentId = org.ParentId,
                    ExtraName = org.EnName,
                    Name = org.OrgName,
                    IsOrg = true,
                    FullName = org.FullName,
                    Children = BuildOrgUserTree(orgs, users, org.Id)
                };
                orgUserTreeOutPut.Children.AddRange(users.Where(p => p.DepartmentId == org.Id).Select(p => new OrgUserTreeOutPut
                {
                    Children = new List<OrgUserTreeOutPut>(),
                    Id = p.Id,
                    ExtraName = p.LoginName,
                    IsOrg = false,
                    Name = p.Name,
                    ParentId = org.Id,
                    FullName = org.FullName
                }).ToList());

                orgUserTreeOutPuts.Add(orgUserTreeOutPut);
            }

            return orgUserTreeOutPuts;
        }

        /// <summary>
        /// 通过组织Id获取组织Id列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public CommonResult<List<string?>> GetOrgIdListByOrgId(GetOrgIdListByOrgIdInput input)
        {
            CommonResult<List<string?>> result = new CommonResult<List<string?>>();

            var orgs = _authRepository.Orm.Select<Organization>().ToList(p => new Organization
            {
                Id = p.Id,
                ParentId = p.ParentId
            });

            var orgIds = new List<string?>();

            GetOrgIdList(orgs, input.OrgId, orgIds);

            result.Result = orgIds;
            result.IsError = false;
            result.Value = EnumBaseResult.OK;
            result.Message = "获取成功";

            return result;
        }

        /// <summary>
        /// 获取组织Id列表
        /// </summary>
        /// <returns></returns>
        public void GetOrgIdList(List<Organization> orgs, string? orgId, List<string?> orgIds)
        {
            var org = orgs.Where(p => p.Id == orgId).FirstOrDefault();
            if (org == null)
            {
                return;
            }
            else
            {
                orgIds.Add(org.Id);
                GetOrgIdList(orgs, org.ParentId, orgIds);
            }
        }
        /// <summary>
        /// 通过组织Id获取所有子组织Id列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public CommonResult<List<string?>> GetSubOrgIdListByOrgId(GetOrgIdListByOrgIdInput input)
        {
            CommonResult<List<string?>> result = new CommonResult<List<string?>>();

            var orgs = _authRepository.Orm.Select<Organization>().ToList(p => new Organization
            {
                Id = p.Id,
                ParentId = p.ParentId
            });

            var orgIds = new List<string?>();

            GetSubOrgIdList(orgs, input.OrgId, orgIds);

            result.Result = orgIds;
            result.IsError = false;
            result.Value = EnumBaseResult.OK;
            result.Message = "获取成功";

            return result;
        }
        /// <summary>
        /// 获取子组织Id列表
        /// </summary>
        /// <returns></returns>
        public void GetSubOrgIdList(List<Organization> orgs, string? orgId, List<string?> orgIds)
        {
            var orgList = orgs.Where(p => p.ParentId == orgId).ToList();
            if (orgList == null || orgList.Count == 0)
            {
                return;
            }
            else
            {
                foreach (var org in orgList)
                {
                    orgIds.Add(org.Id);
                    GetSubOrgIdList(orgs, org.Id, orgIds);
                }
            }
        }

        /// <summary>
        /// 获取全部简易组织信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public CommonResult<List<SimpleOrgOutput>> GetAllSimpleOrgList()
        {
            CommonResult<List<SimpleOrgOutput>> result = new CommonResult<List<SimpleOrgOutput>>();

            result.Result = _authRepository.Orm.Select<Organization>().ToList(p => new SimpleOrgOutput
            {
                Id = p.Id,
                ParentId = p.ParentId
            }); ;
            result.IsError = false;
            result.Value = EnumBaseResult.OK;
            result.Message = "获取成功";

            return result;
        }

        /// <summary>
        /// 通过组织Id获取组织信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public CommonResult<OrgOutPut?> GetOrgInfoByOrgId(GetOrgInfoByOrgIdInput input)
        {
            CommonResult<OrgOutPut?> result = new CommonResult<OrgOutPut?>();

            var orgs = _authRepository.Orm.Select<Organization>().Where(p => p.Id == input.OrgId).ToList(p => new OrgOutPut
            {
                Id = p.Id,
                OrgName = p.OrgName,
                EnName = p.EnName,
                ParentId = p.ParentId,
                FullName = p.FullName,
                Level = p.Level
            });

            result.Result = orgs.FirstOrDefault();

            result.IsError = false;
            result.Value = EnumBaseResult.OK;
            result.Message = "获取成功";

            return result;
        }

        /// <summary>
        /// 通过组织Id列表获取组织列表信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public CommonResult<List<OrgOutPut>?> GetOrgInfosByOrgIds(GetOrgInfosByOrgIdsInput input)
        {
            CommonResult<List<OrgOutPut>?> result = new CommonResult<List<OrgOutPut>?>();

            var orgs = _authRepository.Orm.Select<Organization>()
                .WhereIf(input.OrgIds != null && input.OrgIds.Count > 0, p => input.OrgIds.Contains(p.Id))
                .WhereIf(input.State != null, p => p.State == input.State)
                .ToList(p => new OrgOutPut
                {
                    Id = p.Id,
                    OrgName = p.OrgName,
                    EnName = p.EnName,
                    ParentId = p.ParentId,
                    FullName = p.FullName,
                    Level = p.Level
                });

            result.Result = orgs;

            result.IsError = false;
            result.Value = EnumBaseResult.OK;
            result.Message = "获取成功";

            return result;
        }

        #endregion


        #region 飞书

        public CommonResult UpdateFeishuId(UpdateFeishuIdInput input)
        {


            var result = new CommonResult();

            var user = this._authRepository.Orm.Select<UUIUser>().Where(o => o.Id == input.Uid).ToOne();

            if (string.IsNullOrEmpty(user.Phone))
            {

                result.Message = "该用户手机号为空，无法同步飞书账号";

                return result;

            }

            var getUserId_r = _feiShuClient.GetUserId(new RS.Tool.SDK.FeiShu.Input.GetUserIdInput
            {

                Mobiles = new List<string> {

                 user.Phone
             }
            });

            if (getUserId_r.Code != 0)
            {

                result.Message = getUserId_r.Msg;

                return result;
            }

            if (getUserId_r.Data.UserList.Count() > 0)
            {
                var feishuUser = getUserId_r.Data.UserList.FirstOrDefault();

                if (string.IsNullOrEmpty(feishuUser.UserId))
                {
                    result.Message = "不存在该手机号对应的飞书账号，请联系管理员";

                    return result;
                }
                else
                {


                    var r = this._authRepository.Orm.Update<UUIUser>().Set(o => o.FeiShuUid, feishuUser.UserId).Where(o => o.Id == user.Id).ExecuteAffrows();

                    result.IsError = false;
                    return result;

                }

            }
            else
            {


                result.Message = "不存在该手机号对应的飞书账号，请联系管理员";

                return result;
            }
        }
        #endregion


        #region Token
        public CommonResult CancelAuthToken(CancelAuthTokenInput input)
        {

            var result = new CommonResult();

            if (!string.IsNullOrEmpty(input.Token))
            {
                UserAuthRedis.Del(new string[] { input.Token });
            }
            else if (!string.IsNullOrEmpty(input.Uid))
            {

                var keys = UserAuthRedis.Keys("at_" + SecretHelper.GetMD5(input.Uid) + "_*");

                UserAuthRedis.Del(keys);

            }

            result.IsError = false;

            return result;
        }

        #endregion

        #region 知识类别权限
        public KnowledgeAuth GetKnowledgeAuth(string id)
        {
            return this._authRepository.Orm.Select<KnowledgeAuth>(new { Id = id }).ToOne();
        }

        public int CheckKnowledgeAuth(KnowledgeAuth knowledgeAuth, string? exceptId = null)
        {
            var entity = _authRepository.Orm.Select<KnowledgeAuth>().Where(p => p.DocumentCategory == knowledgeAuth.DocumentCategory && p.DocumentChildCategory == knowledgeAuth.DocumentChildCategory)
                .WhereIf(!string.IsNullOrEmpty(exceptId), p => p.Id != exceptId)
                .First();
            if (entity == null)
            {
                return 0;
            }
            else
            {
                return 1;
            }
        }

        public int UpdateKnowledgeAuth(KnowledgeAuth knowledgeAuth, List<string> relationActions)
        {
            var r = 0;
            using (var trans = _unitOfWorkManager.Begin())
            {

                try
                {

                    r += _authRepository.Orm.Update<KnowledgeAuth>().SetSource(knowledgeAuth).ExecuteAffrows();

                    r += _authRepository.Orm.Delete<KnowledgeAuthRelation>(new { KnowledgeAuthId = knowledgeAuth.Id }).ExecuteAffrows();

                    var newCJWRoleActonRelation = relationActions.Select(o => new KnowledgeAuthRelation
                    {
                        KnowledgeAuthId = knowledgeAuth.Id,
                        ObjectId = o,
                        ObjectType = (int)EnumKnowledgeAuthObjectType.Org

                    }).ToList();

                    r += _authRepository.Orm.Insert<KnowledgeAuthRelation>(newCJWRoleActonRelation).ExecuteAffrows();
                }
                catch
                {

                    trans.Rollback();
                }


            }
            return r;


        }

        public int CreateKnowledgeAuth(KnowledgeAuth knowledgeAuth, List<string> relationActions)
        {

            var r = 0;
            using (var trans = _unitOfWorkManager.Begin())
            {
                try
                {
                    r += _authRepository.Orm.Insert<KnowledgeAuth>(knowledgeAuth).ExecuteAffrows();

                    var newCJWRoleActonRelation = relationActions.Select(o => new KnowledgeAuthRelation
                    {
                        KnowledgeAuthId = knowledgeAuth.Id,
                        ObjectId = o,
                        ObjectType = (int)EnumKnowledgeAuthObjectType.Org

                    }).ToList();

                    r += _authRepository.Orm.Insert<KnowledgeAuthRelation>(newCJWRoleActonRelation).ExecuteAffrows();

                }
                catch
                {
                    trans.Rollback();
                }
            }
            return r;


        }

        public List<KnowledgeAuth> GetKnowledgeAuths(int pagenum, int pagesize, string condition, string orderby, out long count, object para = null)
        {

            var info = this._authRepository.Orm.Select<KnowledgeAuth>().Where(condition, para).OrderBy(orderby).Count(out count).Page(pagenum, pagesize).ToList();
            return info;
        }

        public List<string> GetKnowledgeAuthRelation(string KnowledgeAuthId)
        {
            var info = _authRepository.Orm.Select<KnowledgeAuthRelation>(new { KnowledgeAuthId = KnowledgeAuthId }).ToList(o => o.ObjectId);
            return info;
        }

        public CommonResult<List<KnowledgeAuthOutPut>?> GetKnowledgeAuthInfoList(GetKnowledgeAuthInfoListInput input)
        {
            CommonResult<List<KnowledgeAuthOutPut>?> result = new CommonResult<List<KnowledgeAuthOutPut>?>();

            List<GetKnowledgeAuthCategory> GetKnowledgeAuthCategorys = new List<GetKnowledgeAuthCategory>();

            if (!string.IsNullOrEmpty(input.paras))
            {
                var data1s = input.paras.Split(";");
                foreach (var data1 in data1s)
                {
                    var data2s = data1.Split(",");
                    GetKnowledgeAuthCategorys.Append(new GetKnowledgeAuthCategory
                    {
                        DocumentCategory = data2s[0],
                        DocumentChildCategory = data2s[1]
                    });
                }
            }

            //构造类别子类别条件
            string conditionSql = "";
            List<string> conditions = new List<string>();
            if (GetKnowledgeAuthCategorys != null && GetKnowledgeAuthCategorys.Count > 0)
            {
                GetKnowledgeAuthCategorys.ForEach(p =>
                {
                    conditions.Add($"(\"DocumentCategory\" = '{p.DocumentCategory}' And \"DocumentChildCategory\" = '{p.DocumentChildCategory}')");
                });
            }
            if (conditions.Count > 0)
            {
                conditionSql = string.Join(" Or ", conditions);
            }

            var knowledgeAuths = _authRepository.Orm.Select<KnowledgeAuth>()
                .Where(conditionSql).ToList(p => new
                {
                    Id = p.Id,
                    DocumentCategory = p.DocumentCategory,
                    DocumentChildCategory = p.DocumentChildCategory
                });
            var knowledgeAuthIds = knowledgeAuths.Select(p => p.Id).ToList();

            var objects = _authRepository.Orm.Select<KnowledgeAuthRelation>()
                .Where(p => knowledgeAuthIds.Contains(p.KnowledgeAuthId))
                .ToList(p => new
                {
                    KnowledgeAuthId = p.KnowledgeAuthId,
                    ObjectId = p.ObjectId
                });

            //构造返回结果
            result.Result = new List<KnowledgeAuthOutPut>();
            knowledgeAuths.ForEach(x =>
            {
                KnowledgeAuthOutPut knowledgeAuthOutPut = new KnowledgeAuthOutPut()
                {
                    DocumentCategory = x.DocumentCategory,
                    DocumentChildCategory = x.DocumentChildCategory,
                    ObjectIds = new List<string>()
                };

                knowledgeAuthOutPut.ObjectIds = objects.Where(p => p.KnowledgeAuthId == x.Id).Select(p => p.ObjectId).ToList();
                result.Result.Add(knowledgeAuthOutPut);
            });

            result.IsError = false;
            result.Value = EnumBaseResult.OK;
            result.Message = "获取成功";

            return result;
        }

        public int DeleteKnowledgeAuth(string id)
        {
            var r = 0;
            using (var trans = _unitOfWorkManager.Begin())
            {
                r += this._authRepository.Orm.Delete<KnowledgeAuth>().Where(m => m.Id == id).ExecuteAffrows();
                r += this._authRepository.Orm.Delete<KnowledgeAuthRelation>().Where(m => m.KnowledgeAuthId == id).ExecuteAffrows();
            }
            return r;

        }
        #endregion

        #region 知识中心组织架构权限管理

        public CommonResult AddKnowledgeAuthOrganization(AddKnowledgeAuthOrganizationInput input)
        {

            var result = new CommonResult();
            result.IsError = true;
            //新增
            if (string.IsNullOrEmpty(input.KnowledgeAuthOrganizationId))
            {
                var model = new KnowledgeAuthOrganization()
                {
                    Type = 2,
                    Organization = input.Organization,
                    Category = input.Category,
                    CreateUserId = input.Uid
                };
                _authRepository.Orm.Insert<KnowledgeAuthOrganization>(model).ExecuteAffrows();
            }
            //修改
            else
            {
                var model = this._authRepository.Orm.Select<KnowledgeAuthOrganization>().Where(o => o.Id == input.KnowledgeAuthOrganizationId).ToOne();
                if (model == null)
                {
                    result.Message = $"该节点{input.KnowledgeAuthOrganizationId}不存在";
                    return result;
                }
                model.Organization = input.Organization;
                if (model.Type == 2)
                {
                    model.Category = input.Category;
                }
                model.UpdateUserId = input.Uid;
                this._authRepository.Orm.Update<KnowledgeAuthOrganization>().SetSource(model).ExecuteAffrows();
            }
            result.IsError = false;
            result.Message = string.IsNullOrEmpty(input.KnowledgeAuthOrganizationId) ? "添加成功" : "修改成功";
            result.Value = RS.BaseModel.Enum.EnumBaseResult.OK;
            return result;

        }

        public CommonResult DeleteKnowledgeAuthOrganization(DeleteKnowledgeAuthOrganizationInput input)
        {
            var result = new CommonResult();
            this._authRepository.Orm.Delete<KnowledgeAuthOrganization>().Where(p => p.Id == input.KnowledgeAuthOrganizationId).ExecuteAffrows();
            result.IsError = false;
            result.Message = "删除成功";
            return result;
        }

        public CommonResult<PageModel<GetKnowledgeAuthOrganizationListOut>> GetKnowledgeAuthOrganizationList(GetKnowledgeAuthOrganizationListInput input)
        {

            var result = new CommonResult<PageModel<GetKnowledgeAuthOrganizationListOut>>();
            var info = new List<GetKnowledgeAuthOrganizationListOut>();
            long count = 0;
            info = this._authRepository.Orm.Select<KnowledgeAuthOrganization>().Where(m => m.Type == input.Type).OrderByDescending(o => o.CreateTime).Count(out count).
                Page(input.Page, input.PageSize).ToList<GetKnowledgeAuthOrganizationListOut>(o => new GetKnowledgeAuthOrganizationListOut
                {
                    Id = o.Id,
                    Type = o.Type,
                    Organization = o.Organization,
                    Category = o.Category,
                });

            result.IsError = false;
            result.Result = new PageModel<GetKnowledgeAuthOrganizationListOut>
            {
                Data = info,
                DataCount = count,
                Page = input.Page,
                PageSize = input.PageSize,
                PageCount = Convert.ToInt32(Math.Ceiling((decimal)count / input.PageSize))
            };
            return result;
        }
        public CommonResult<GetKnowledgeAuthOrganizationApiListOut> GetKnowledgeAuthOrganizationApiList(GetKnowledgeAuthOrganizationApiListInput input)
        {

            var result = new CommonResult<GetKnowledgeAuthOrganizationApiListOut>();
            var userList = this._authRepository.Orm.Select<UUIUser>().ToList();

            var user = userList.Where(m => m.Id == input.Uid).FirstOrDefault();
            var orgs = _authRepository.Orm.Select<Organization>().ToList(p => new Organization
            {
                Id = p.Id,
                ParentId = p.ParentId
            });
            string firstOrgId = "";
            List<string?> resultCategoryList = new List<string?>();
            var info = this._authRepository.Orm.Select<KnowledgeAuthOrganization>().ToList();
            GetFirstOrg(orgs, info, user.DepartmentId, ref firstOrgId, ref resultCategoryList);
            List<UUIUser> resultUserList = new List<UUIUser>();
            GetUserListByOrg(orgs, userList, ref resultUserList, firstOrgId);
            result.Result = new GetKnowledgeAuthOrganizationApiListOut()
            {
                resultCategoryList = resultCategoryList.Distinct().ToList(),
                resultUserList = resultUserList
            };
            result.IsError = false;
            return result;
        }
        public void GetFirstOrg(List<Organization> orgs, List<KnowledgeAuthOrganization> organization, string orgId, ref string? firstOrgId, ref List<string?> categoryList)
        {
            var o = organization.Where(m => m.Type == 1 && m.Organization.Contains(orgId)).FirstOrDefault();
            var o2 = organization.Where(m => m.Type == 2 && m.Organization.Contains(orgId));
            if (o != null)
            {
                firstOrgId = orgId;
            }
            if (o2 != null)
            {
                foreach (var item in o2)
                {
                    categoryList = categoryList.Concat(item.Category).ToList();
                }
            }
            var org = orgs.Where(p => p.Id == orgId).FirstOrDefault();
            if (org == null)
            {
                return;
            }
            else
            {
                GetFirstOrg(orgs, organization, org.ParentId, ref firstOrgId, ref categoryList);
            }
        }

        public void GetUserListByOrg(List<Organization> orgs, List<UUIUser> userList, ref List<UUIUser> resultUserList, string orgId)
        {
            if (orgId == null || orgId == "")
            {
                return;
            }
            var o = userList.Where(m => m.DepartmentId == orgId).ToList();
            if (o != null && o.Count() > 0)
            {
                resultUserList = resultUserList.Concat(o).ToList();
            }
            var orgList = orgs.Where(p => p.ParentId == orgId).ToList();
            foreach (var org in orgList)
            {
                GetUserListByOrg(orgs, userList, ref resultUserList, org.Id);
            }
        }

        #endregion
        /// <summary>
        /// 添加用户访问记录
        /// </summary>
        /// <returns></returns>
        public CommonResult AddUserVisitRecord(string ip, string uid)
        {
            var result = new CommonResult();
            Task.Run(() =>
            {
                using (var trans = _unitOfWorkManager.Begin())
                {
                    try
                    {
                        int year = DateTime.Now.Year;
                        int month = DateTime.Now.Month;
                        int day = DateTime.Now.Day;

                        UserVisitRecord userVisitRecord = new UserVisitRecord();
                        userVisitRecord.Ip = ip;
                        userVisitRecord.Year = year;
                        userVisitRecord.Month = month;
                        userVisitRecord.Day = day;
                        userVisitRecord.CreateUserId = uid;
                        _authRepository.Orm.Insert(userVisitRecord).AsTable(oldname => $"{oldname}_{year}").ExecuteAffrows();
                        trans.Commit();

                        var model = _authRepository.Orm.Select<UserVisitSta>().Where(m => m.Year == year && m.Month == month && m.Day == day).ToList().FirstOrDefault();
                        if (model == null)
                        {
                            UserVisitSta userVisitSta = new UserVisitSta();
                            userVisitSta.Year = year;
                            userVisitSta.Month = month;
                            userVisitSta.Day = day;
                            userVisitSta.Count = 1;
                            userVisitSta.CreateUserId = uid;
                            _authRepository.Orm.Insert<UserVisitSta>(userVisitSta).ExecuteAffrows();
                        }
                        else
                        {
                            _authRepository.Orm.Update<UserVisitSta>().Where(m => m.Id == model.Id).Set(n => n.Count, model.Count + 1).ExecuteAffrows();
                        }
                    }
                    catch
                    {
                        trans.Rollback();
                    }
                }

            });
            result.IsError = false;
            result.Value = EnumBaseResult.OK;
            return result;
        }
        /// <summary>
        /// 添加用户模块访问记录
        /// </summary>
        /// <returns></returns>
        public CommonResult AddUserModuleVisitRecord(string ip, string module, string uid)
        {
            var result = new CommonResult();
            Task.Run(() =>
            {
                using (var trans = _unitOfWorkManager.Begin())
                {
                    try
                    {
                        int year = DateTime.Now.Year;
                        int month = DateTime.Now.Month;
                        int day = DateTime.Now.Day;

                        UserModuleVisitRecord userModuleVisitRecord = new UserModuleVisitRecord();
                        userModuleVisitRecord.Ip = ip;
                        userModuleVisitRecord.Year = year;
                        userModuleVisitRecord.Month = month;
                        userModuleVisitRecord.Day = day;
                        userModuleVisitRecord.Module = module;
                        userModuleVisitRecord.CreateUserId = uid;
                        _authRepository.Orm.Insert(userModuleVisitRecord).AsTable(oldname => $"{oldname}_{year}").ExecuteAffrows();
                        trans.Commit();

                        var model = _authRepository.Orm.Select<UserModuleVisitSta>().Where(m => m.Year == year && m.Month == month && m.Day == day && m.Module == module).ToList().FirstOrDefault();
                        if (model == null)
                        {
                            UserModuleVisitSta userModuleVisitSta = new UserModuleVisitSta();
                            userModuleVisitSta.Year = year;
                            userModuleVisitSta.Month = month;
                            userModuleVisitSta.Day = day;
                            userModuleVisitSta.Module = module;
                            userModuleVisitSta.Count = 1;
                            userModuleVisitSta.CreateUserId = uid;
                            _authRepository.Orm.Insert<UserModuleVisitSta>(userModuleVisitSta).ExecuteAffrows();
                        }
                        else
                        {
                            _authRepository.Orm.Update<UserModuleVisitSta>().Where(m => m.Id == model.Id).Set(n => n.Count, model.Count + 1).ExecuteAffrows();
                        }
                    }
                    catch
                    {
                        trans.Rollback();
                    }
                }

            });
            result.IsError = false;
            result.Value = EnumBaseResult.OK;
            return result;
        }
    }
}